From a6f63598adb880a75e1571aac58338c17fa7ad53 Mon Sep 17 00:00:00 2001 From: Amiti Uttarwar Date: Tue, 28 Jan 2020 15:26:32 -0800 Subject: [util] allow scheduler to be mocked Add MockForward method to the scheduler that mimics going into the future by rescheduling all items on the taskQueue to be sooner. --- src/scheduler.cpp | 22 ++++++++++++++++++++++ src/scheduler.h | 7 +++++++ 2 files changed, 29 insertions(+) (limited to 'src') diff --git a/src/scheduler.cpp b/src/scheduler.cpp index 927a3f3820..72cca89d99 100644 --- a/src/scheduler.cpp +++ b/src/scheduler.cpp @@ -114,6 +114,28 @@ void CScheduler::scheduleFromNow(CScheduler::Function f, int64_t deltaMilliSecon schedule(f, boost::chrono::system_clock::now() + boost::chrono::milliseconds(deltaMilliSeconds)); } +void CScheduler::MockForward(boost::chrono::seconds delta_seconds) +{ + assert(delta_seconds.count() > 0 && delta_seconds < boost::chrono::hours{1}); + + { + boost::unique_lock lock(newTaskMutex); + + // use temp_queue to maintain updated schedule + std::multimap temp_queue; + + for (const auto& element : taskQueue) { + temp_queue.emplace_hint(temp_queue.cend(), element.first - delta_seconds, element.second); + } + + // point taskQueue to temp_queue + taskQueue = std::move(temp_queue); + } + + // notify that the taskQueue needs to be processed + newTaskScheduled.notify_one(); +} + static void Repeat(CScheduler* s, CScheduler::Function f, int64_t deltaMilliSeconds) { f(); diff --git a/src/scheduler.h b/src/scheduler.h index 7080adf34c..d18be0ea5e 100644 --- a/src/scheduler.h +++ b/src/scheduler.h @@ -55,6 +55,13 @@ public: // need more accurate scheduling, don't use this method. void scheduleEvery(Function f, int64_t deltaMilliSeconds); + /** + * Mock the scheduler to fast forward in time. + * Iterates through items on taskQueue and reschedules them + * to be delta_seconds sooner. + */ + void MockForward(boost::chrono::seconds delta_seconds); + // To keep things as simple as possible, there is no unschedule. // Services the queue 'forever'. Should be run in a thread, -- cgit v1.2.3