]> git.tdb.fi Git - libs/core.git/blob - source/time/timer.h
Additional adjustments for Poller
[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/attributes.h>
7 #include <msp/core/mutex.h>
8 #include <msp/core/noncopyable.h>
9 #include <msp/core/semaphore.h>
10 #include "timedelta.h"
11 #include "timestamp.h"
12
13 namespace Msp {
14 namespace Time {
15
16 /**
17 A class for executing functions in a deferred or periodical fashion.  The add a
18 timer, use one of the add functions and connect a functor to the timeout signal
19 of the returned slot.
20
21 This class is thread-safe, to allow running timers in a separate thread.
22 */
23 class Timer: private NonCopyable
24 {
25 public:
26         class Slot
27         {
28         public:
29                 sigc::signal<bool> signal_timeout;
30         
31         private:
32                 TimeDelta interval;
33                 TimeStamp timeout;
34         
35         public:
36                 Slot(const TimeDelta &);
37                 Slot(const TimeStamp &);
38                 const TimeStamp &get_timeout() const { return timeout; }
39                 bool increment();
40         };
41
42 private:
43         struct SlotProxy
44         {
45                 Slot *slot;
46
47                 SlotProxy(Slot *);
48                 bool operator<(const SlotProxy &) const;
49         };
50
51         std::vector<SlotProxy> slots;
52         Semaphore sem;
53         Mutex mutex;
54         bool blocking;
55
56 public:
57         Timer();
58         ~Timer();
59
60         /** Adds a timer that will be executed periodically as long as the timeout
61         signal hander returns true. */
62         Slot &add(const TimeDelta &);
63
64         /** Adds a timer that will be executed once at a specific time.  The return
65         value of the timeout signal handler is ignored. */
66         Slot &add(const TimeStamp &);
67
68         /** Cancels a previously added timer. */
69         void cancel(Slot &);
70
71         /** Deprecated.  Use one of the other overloads. */
72         DEPRECATED void tick(bool block);
73
74         /** Waits until a timer expires, then executes it.  If no timers have been
75         set, blocks until one is added from another thread. */
76         void tick();
77
78         /** Waits until a timer expires but at most the specified amount of time.
79         If a timer did expire before the timeout, it is executed. */
80         void tick(const TimeDelta &);
81
82 private:
83         void do_tick(const TimeDelta &);
84
85 public:
86         TimeStamp get_next_timeout() const;
87 };
88
89 } // namespace Time
90 } // namespace Msp
91
92 #endif