|
6 | 6 | #include <future> |
7 | 7 | #include <mutex> |
8 | 8 | #include <string> |
| 9 | +#include <unordered_map> |
9 | 10 | #include <utility> |
10 | 11 |
|
11 | 12 | #include "detail/PriorityQueue.hpp" |
@@ -62,21 +63,46 @@ class Scheduler { |
62 | 63 | this->processTasks(); |
63 | 64 | } |
64 | 65 | }; |
| 66 | + std::lock_guard<std::mutex> guard(_mutex); |
65 | 67 | this->addTask(id, std::move(functor), timepoint); |
66 | 68 |
|
67 | 69 | return future; |
68 | 70 | } |
69 | 71 |
|
| 72 | + template <typename Duration, class F, class... Args> |
| 73 | + void scheduleEvery(const std::string& id, Duration delay, F&& function, Args&&... args) { |
| 74 | + auto task = std::bind(std::forward<F>(function), std::forward<Args>(args)...); |
| 75 | + |
| 76 | + auto periodicTask = [this, id, task = std::move(task), delay]() { |
| 77 | + task(); |
| 78 | + |
| 79 | + { |
| 80 | + std::lock_guard<std::mutex> guard(_mutex); |
| 81 | + |
| 82 | + --_workerCount; |
| 83 | + auto periodicTask = _periodicTasks.find(id); |
| 84 | + if (periodicTask == _periodicTasks.end()) { |
| 85 | + return; |
| 86 | + } |
| 87 | + this->addTask(id, periodicTask->second, Detail::Clock::now() + delay); |
| 88 | + } |
| 89 | + }; |
| 90 | + std::lock_guard<std::mutex> guard(_mutex); |
| 91 | + this->addTask(id, std::move(periodicTask), Detail::Clock::now() + delay, true); |
| 92 | + } |
| 93 | + |
70 | 94 | void remove(const std::string& id); |
71 | 95 | bool isScheduled(const std::string& id) const; |
72 | 96 |
|
73 | 97 | private: |
74 | | - void addTask(const std::string& id, std::function<void()> functor, Detail::Timepoint timepoint); |
| 98 | + void addTask(const std::string& id, std::function<void()> functor, Detail::Timepoint timepoint, |
| 99 | + bool reschedulable = false); |
75 | 100 | void processTasks(); |
76 | 101 |
|
77 | 102 | private: |
78 | 103 | std::shared_ptr<Detail::Threadpool> _threadpool; |
79 | 104 | Detail::PriorityQueue<TimedTask, std::greater<>> _tasks; |
| 105 | + std::unordered_map<std::string, std::function<void()>> _periodicTasks; |
80 | 106 | std::hash<std::string> _hasher; |
81 | 107 | mutable std::mutex _mutex; |
82 | 108 | size_t _maxWorkers; |
|
0 commit comments