]> git.tdb.fi Git - libs/core.git/blob - source/time/timer.h
Split Timer::tick into two overloads
[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         bool blocking;
53
54 public:
55         Timer();
56         ~Timer();
57
58         /** Adds a timer that will be executed periodically as long as the timeout
59         signal hander returns true. */
60         Slot &add(const TimeDelta &);
61
62         /** Adds a timer that will be executed once at a specific time.  The return
63         value of the timeout signal handler is ignored. */
64         Slot &add(const TimeStamp &);
65
66         /** Cancels a previously added timer. */
67         void cancel(Slot &);
68
69         /** Deprecated.  Use one of the other overloads. */
70         void tick(bool block);
71
72         /** Waits until a timer expires, then executes it.  If no timers have been
73         set, blocks until one is added from another thread. */
74         void tick();
75
76         /** Waits until a timer expires but at most the specified amount of time.
77         If a timer did expire before the timeout, it is executed. */
78         void tick(const TimeDelta &);
79
80 private:
81         void do_tick(const TimeDelta &);
82
83 public:
84         TimeStamp get_next_timeout() const;
85 };
86
87 } // namespace Time
88 } // namespace Msp
89
90 #endif