xrpld
Loading...
Searching...
No Matches
Scheduler.cpp
1#include <csf/Scheduler.h>
2
3#include <gtest/gtest.h>
4
5#include <set>
6
7namespace xrpl::test {
8
9TEST(SchedulerTest, scheduler)
10{
11 using namespace std::chrono_literals;
12 csf::Scheduler scheduler;
13 std::set<int> seen;
14
15 scheduler.in(1s, [&] { seen.insert(1); });
16 scheduler.in(2s, [&] { seen.insert(2); });
17 auto token = scheduler.in(3s, [&] { seen.insert(3); });
18 scheduler.at(scheduler.now() + 4s, [&] { seen.insert(4); });
19 scheduler.at(scheduler.now() + 8s, [&] { seen.insert(8); });
20
21 auto start = scheduler.now();
22
23 // Process first event
24 EXPECT_TRUE(seen.empty());
25 EXPECT_TRUE(scheduler.stepOne());
26 EXPECT_TRUE(seen == std::set<int>({1}));
27 EXPECT_TRUE(scheduler.now() == (start + 1s));
28
29 // No processing if stepping until current time
30 EXPECT_TRUE(scheduler.stepUntil(scheduler.now()));
31 EXPECT_TRUE(seen == std::set<int>({1}));
32 EXPECT_TRUE(scheduler.now() == (start + 1s));
33
34 // Process next event
35 EXPECT_TRUE(scheduler.stepFor(1s));
36 EXPECT_TRUE(seen == std::set<int>({1, 2}));
37 EXPECT_TRUE(scheduler.now() == (start + 2s));
38
39 // Don't process cancelled event, but advance clock
40 scheduler.cancel(token);
41 EXPECT_TRUE(scheduler.stepFor(1s));
42 EXPECT_TRUE(seen == std::set<int>({1, 2}));
43 EXPECT_TRUE(scheduler.now() == (start + 3s));
44
45 // Process until 3 seen ints
46 EXPECT_TRUE(scheduler.stepWhile([&]() { return seen.size() < 3; }));
47 EXPECT_TRUE(seen == std::set<int>({1, 2, 4}));
48 EXPECT_TRUE(scheduler.now() == (start + 4s));
49
50 // Process the rest
51 EXPECT_TRUE(scheduler.step());
52 EXPECT_TRUE(seen == std::set<int>({1, 2, 4, 8}));
53 EXPECT_TRUE(scheduler.now() == (start + 8s));
54
55 // Process the rest again doesn't advance
56 EXPECT_TRUE(!scheduler.step());
57 EXPECT_TRUE(seen == std::set<int>({1, 2, 4, 8}));
58 EXPECT_TRUE(scheduler.now() == (start + 8s));
59}
60
61} // namespace xrpl::test
Simulated discrete-event scheduler.
bool step()
Run the scheduler until no events remain.
CancelToken at(time_point const &when, Function &&f)
Schedule an event at a specific time.
time_point now() const
Return the current network time.
bool stepUntil(time_point const &until)
Run the scheduler until the specified time.
void cancel(CancelToken const &token)
Cancel a timer.
CancelToken in(duration const &delay, Function &&f)
Schedule an event after a specified duration passes.
bool stepOne()
Run the scheduler for up to one event.
bool stepWhile(Function &&func)
Run the scheduler while a condition is true.
bool stepFor(std::chrono::duration< Period, Rep > const &amount)
Run the scheduler until time has elapsed.
T empty(T... args)
T insert(T... args)
TEST(UnitsTest, types)
Definition Units.cpp:16