class Scheduler {
ThreadPool pool_{4}; // 工作线程池
Timer timer_; // 定时器
public:
// 立即执行(线程池的任务)
template <typename F>
auto execute(F&& f) {
return pool_.enqueue(std::forward<F>(f));
}
// 延迟执行(先经过定时器,到时间后丢给线程池)
template <typename F>
auto executeAfter(std::chrono::milliseconds delay, F&& f) {
using ReturnType = std::invoke_result_t<F>;
auto promise = std::make_shared<std::promise<ReturnType>>();
auto future = promise->get_future();
timer_.addTimer(delay, [this, f = std::forward<F>(f), promise]() mutable {
pool_.enqueue([f = std::move(f), promise]() mutable {
if constexpr (std::is_void_v<ReturnType>) {
f();
promise->set_value();
} else {
promise->set_value(f());
}
});
});
return future;
}
// 周期执行
template <typename F>
void executeEvery(std::chrono::milliseconds interval, F&& f) {
timer_.addTimer(interval, interval, [this, f = std::forward<F>(f)]() mutable {
pool_.enqueue(f);
});
}
};