]> git.tdb.fi Git - libs/core.git/blob - source/time/timer.h
Rewrite Timer to use a heap instead of set to deal with duplicate timeouts
[libs/core.git] / source / time / timer.h
1 /* $Id$
2
3 This file is part of libmspcore     
4 Copyright © 2006, 2009  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #ifndef MSP_TIME_TIMER_H_
9 #define MSP_TIME_TIMER_H_
10
11 #include <vector>
12 #include <sigc++/sigc++.h>
13 #include "../core/mutex.h"
14 #include "../core/semaphore.h"
15 #include "timedelta.h"
16 #include "timestamp.h"
17
18 namespace Msp {
19 namespace Time {
20
21 /**
22 A class for executing functions in a deferred or periodical fashion.  The add a
23 timer, use one of the add functions and connect a functor to the timeout signal
24 of the returned slot.
25
26 This class is thread-safe, to allow running timers in a separate thread.
27 */
28 class Timer
29 {
30 public:
31         class Slot
32         {
33         public:
34                 sigc::signal<bool> signal_timeout;
35         
36         private:
37                 TimeDelta interval;
38                 TimeStamp timeout;
39         
40         public:
41                 Slot(const TimeDelta &);
42                 Slot(const TimeStamp &);
43                 const TimeStamp &get_timeout() const { return timeout; }
44                 bool increment();
45         };
46
47 private:
48         struct SlotProxy
49         {
50                 Slot *slot;
51
52                 SlotProxy(Slot *);
53                 bool operator<(const SlotProxy &) const;
54         };
55
56         std::vector<SlotProxy> slots;
57         Semaphore sem;
58         Mutex mutex;
59
60 public:
61         ~Timer();
62
63         /**
64         Adds a timer that will be executed periodically as long as the timeout
65         signal hander returns true.
66         */
67         Slot &add(const TimeDelta &);
68
69         /**
70         Adds a timer that will be executed once at a specific time.  The return
71         value of the timeout signal handler is ignored.
72         */
73         Slot &add(const TimeStamp &);
74
75         /**
76         Cancels a previously added timer.
77         */
78         void cancel(Slot &);
79
80         /**
81         Checks all timers, executing any that have timed out.  If block is true,
82         waits until one times out.
83
84         Note: If there are no active timers when a blocking tick is executed, it
85         won't return until a timer is added from another thread.
86         */
87         void tick(bool block=true);
88
89         TimeStamp get_next_timeout() const;
90 };
91
92 } // namespace Time
93 } // namespace Msp
94
95 #endif