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