Use the override specifier (C++11) where we expect to be overriding the virtual funct...
[bitcoinplatinum.git] / src / scheduler.h
blob27412a15b465b1a98cbc46613fc17b11c45b40cd
1 // Copyright (c) 2015 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_SCHEDULER_H
6 #define BITCOIN_SCHEDULER_H
8 //
9 // NOTE:
10 // boost::thread / boost::chrono should be ported to std::thread / std::chrono
11 // when we support C++11.
13 #include <boost/chrono/chrono.hpp>
14 #include <boost/thread.hpp>
15 #include <map>
18 // Simple class for background tasks that should be run
19 // periodically or once "after a while"
21 // Usage:
23 // CScheduler* s = new CScheduler();
24 // s->scheduleFromNow(doSomething, 11); // Assuming a: void doSomething() { }
25 // s->scheduleFromNow(std::bind(Class::func, this, argument), 3);
26 // boost::thread* t = new boost::thread(boost::bind(CScheduler::serviceQueue, s));
28 // ... then at program shutdown, clean up the thread running serviceQueue:
29 // t->interrupt();
30 // t->join();
31 // delete t;
32 // delete s; // Must be done after thread is interrupted/joined.
35 class CScheduler
37 public:
38 CScheduler();
39 ~CScheduler();
41 typedef std::function<void(void)> Function;
43 // Call func at/after time t
44 void schedule(Function f, boost::chrono::system_clock::time_point t);
46 // Convenience method: call f once deltaSeconds from now
47 void scheduleFromNow(Function f, int64_t deltaMilliSeconds);
49 // Another convenience method: call f approximately
50 // every deltaSeconds forever, starting deltaSeconds from now.
51 // To be more precise: every time f is finished, it
52 // is rescheduled to run deltaSeconds later. If you
53 // need more accurate scheduling, don't use this method.
54 void scheduleEvery(Function f, int64_t deltaMilliSeconds);
56 // To keep things as simple as possible, there is no unschedule.
58 // Services the queue 'forever'. Should be run in a thread,
59 // and interrupted using boost::interrupt_thread
60 void serviceQueue();
62 // Tell any threads running serviceQueue to stop as soon as they're
63 // done servicing whatever task they're currently servicing (drain=false)
64 // or when there is no work left to be done (drain=true)
65 void stop(bool drain=false);
67 // Returns number of tasks waiting to be serviced,
68 // and first and last task times
69 size_t getQueueInfo(boost::chrono::system_clock::time_point &first,
70 boost::chrono::system_clock::time_point &last) const;
72 private:
73 std::multimap<boost::chrono::system_clock::time_point, Function> taskQueue;
74 boost::condition_variable newTaskScheduled;
75 mutable boost::mutex newTaskMutex;
76 int nThreadsServicingQueue;
77 bool stopRequested;
78 bool stopWhenEmpty;
79 bool shouldStop() { return stopRequested || (stopWhenEmpty && taskQueue.empty()); }
82 #endif