-/*
-This file is part of libmspcore
-Copyright © 2006 Mikko Rasa, Mikkosoft Productions
-Distributed under the LGPL
-*/
-
#ifndef MSP_TIME_TIMER_H_
#define MSP_TIME_TIMER_H_
-#include <queue>
+#include <vector>
#include <sigc++/sigc++.h>
-#include "../core/mutex.h"
-#include "../core/semaphore.h"
+#include <msp/core/mspcore_api.h>
+#include <msp/core/mutex.h>
+#include <msp/core/noncopyable.h>
+#include <msp/core/semaphore.h>
#include "timedelta.h"
#include "timestamp.h"
This class is thread-safe, to allow running timers in a separate thread.
*/
-class Timer
+class MSPCORE_API Timer: private NonCopyable
{
public:
class Slot
Slot(const TimeStamp &);
const TimeStamp &get_timeout() const { return timeout; }
bool increment();
- bool operator<(const Slot &) const;
};
private:
- typedef bool (*fSlotCompare)(Slot *, Slot *);
+ struct SlotProxy
+ {
+ Slot *slot;
+
+ bool operator<(const SlotProxy &) const;
+ };
- std::priority_queue<Slot *, std::vector<Slot *>, fSlotCompare> slots;
+ std::vector<SlotProxy> slots;
Semaphore sem;
Mutex mutex;
+ bool blocking = false;
public:
Timer();
~Timer();
- /**
- Adds a timer that will be executed periodically as long as the timeout
- signal hander returns true.
- */
+ /** Adds a timer that will be executed periodically as long as the timeout
+ signal hander returns true. */
Slot &add(const TimeDelta &);
- /**
- Adds a timer that will be executed once at a specific time. The return
- value of the timeout signal handler is ignored.
- */
+ /** Adds a timer that will be executed once at a specific time. The return
+ value of the timeout signal handler is ignored. */
Slot &add(const TimeStamp &);
- /**
- Checks all timers, executing any that have timed out. If block is true,
- waits until one times out.
+ /** Cancels a previously added timer. */
+ void cancel(Slot &);
+
+ /** Waits until a timer expires, then executes it. If no timers have been
+ set, blocks until one is added from another thread. */
+ void tick();
+
+ /** Waits until a timer expires but at most the specified amount of time.
+ If a timer did expire before the timeout, it is executed. */
+ void tick(const TimeDelta &);
- Note: If there are no active timers when a blocking tick is executed, it
- won't return until a timer is added from another thread.
- */
- void tick(bool block=true);
private:
- static bool slot_compare(Slot *, Slot *);
+ void do_tick(const TimeDelta &);
+
+public:
+ TimeStamp get_next_timeout() const;
};
} // namespace Time