Skip to content

Commit a6f6359

Browse files
committed
[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.
1 parent aabec94 commit a6f6359

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/scheduler.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,28 @@ void CScheduler::scheduleFromNow(CScheduler::Function f, int64_t deltaMilliSecon
114114
schedule(f, boost::chrono::system_clock::now() + boost::chrono::milliseconds(deltaMilliSeconds));
115115
}
116116

117+
void CScheduler::MockForward(boost::chrono::seconds delta_seconds)
118+
{
119+
assert(delta_seconds.count() > 0 && delta_seconds < boost::chrono::hours{1});
120+
121+
{
122+
boost::unique_lock<boost::mutex> lock(newTaskMutex);
123+
124+
// use temp_queue to maintain updated schedule
125+
std::multimap<boost::chrono::system_clock::time_point, Function> temp_queue;
126+
127+
for (const auto& element : taskQueue) {
128+
temp_queue.emplace_hint(temp_queue.cend(), element.first - delta_seconds, element.second);
129+
}
130+
131+
// point taskQueue to temp_queue
132+
taskQueue = std::move(temp_queue);
133+
}
134+
135+
// notify that the taskQueue needs to be processed
136+
newTaskScheduled.notify_one();
137+
}
138+
117139
static void Repeat(CScheduler* s, CScheduler::Function f, int64_t deltaMilliSeconds)
118140
{
119141
f();

src/scheduler.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,13 @@ class CScheduler
5555
// need more accurate scheduling, don't use this method.
5656
void scheduleEvery(Function f, int64_t deltaMilliSeconds);
5757

58+
/**
59+
* Mock the scheduler to fast forward in time.
60+
* Iterates through items on taskQueue and reschedules them
61+
* to be delta_seconds sooner.
62+
*/
63+
void MockForward(boost::chrono::seconds delta_seconds);
64+
5865
// To keep things as simple as possible, there is no unschedule.
5966

6067
// Services the queue 'forever'. Should be run in a thread,

0 commit comments

Comments
 (0)