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