My Project
3.7.9
C++ Distributed Hash Table
Toggle main menu visibility
Loading...
Searching...
No Matches
include
opendht
scheduler.h
1
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
2
// SPDX-License-Identifier: MIT
3
#pragma once
4
5
#include "utils.h"
6
7
#include <functional>
8
#include <map>
9
10
namespace
dht
{
11
18
class
Scheduler
19
{
20
public
:
21
struct
Job
22
{
23
Job(std::function<
void
()>&& f, time_point t)
24
: do_(std::move(f))
25
, t_(t)
26
{}
27
std::function<void()> do_;
28
const
time_point t_;
29
void
cancel() { do_ = {}; }
30
};
31
40
Sp<Scheduler::Job>
add
(time_point t, std::function<
void
()>&& job_func)
41
{
42
auto
job = std::make_shared<Job>(std::move(job_func), t);
43
if
(t != time_point::max())
44
timers.emplace(std::move(t), job);
45
return
job;
46
}
47
54
void
edit
(Sp<Scheduler::Job>& job, time_point t)
55
{
56
if
(not job)
57
return
;
58
// std::function move doesn't garantee to leave the object empty.
59
// Force clearing old value.
60
auto
task = std::move(job->do_);
61
cancel(job);
62
job =
add
(t, std::move(task));
63
}
64
65
bool
cancel(Sp<Scheduler::Job>& job)
66
{
67
if
(job) {
68
job->cancel();
69
for
(
auto
r = timers.equal_range(job->t_); r.first != r.second; ++r.first) {
70
if
(r.first->second == job) {
71
timers.erase(r.first);
72
job.reset();
73
return
true
;
74
}
75
}
76
}
77
return
false
;
78
}
79
85
time_point
run
()
86
{
87
while
(not timers.empty()) {
88
auto
timer = timers.begin();
89
/*
90
* Running jobs scheduled before "now" prevents run+rescheduling
91
* loops before this method ends. It is garanteed by the fact that a
92
* job will at least be scheduled for "now" and not before.
93
*/
94
if
(timer->first > now)
95
break
;
96
97
auto
job = std::move(timer->second);
98
timers.erase(timer);
99
100
if
(job->do_)
101
job->do_();
102
}
103
return
getNextJobTime();
104
}
105
106
inline
time_point getNextJobTime()
const
{
return
timers.empty() ? time_point::max() : timers.begin()->first; }
107
112
inline
const
time_point&
time
()
const
{
return
now; }
113
inline
time_point syncTime() {
return
(now = clock::now()); }
114
inline
void
syncTime(
const
time_point& n) { now = n; }
115
116
private
:
117
time_point now {clock::now()};
118
std::multimap<time_point, Sp<Job>> timers {};
/* the jobs ordered by time */
119
};
120
121
}
// namespace dht
dht::Scheduler
Job scheduler.
Definition
scheduler.h:19
dht::Scheduler::add
Sp< Scheduler::Job > add(time_point t, std::function< void()> &&job_func)
Definition
scheduler.h:40
dht::Scheduler::time
const time_point & time() const
Definition
scheduler.h:112
dht::Scheduler::run
time_point run()
Definition
scheduler.h:85
dht::Scheduler::edit
void edit(Sp< Scheduler::Job > &job, time_point t)
Definition
scheduler.h:54
dht
Definition
callbacks.h:17
Generated on
for My Project by
1.17.0