File indexing completed on 2025-01-30 10:24:43
0001
0002
0003
0004 #pragma once
0005
0006
0007
0008
0009
0010
0011
0012 #include <chrono>
0013 #include <condition_variable>
0014 #include <functional>
0015 #include <mutex>
0016 #include <thread>
0017 namespace spdlog {
0018 namespace details {
0019
0020 class SPDLOG_API periodic_worker
0021 {
0022 public:
0023 template<typename Rep, typename Period>
0024 periodic_worker(const std::function<void()> &callback_fun, std::chrono::duration<Rep, Period> interval)
0025 {
0026 active_ = (interval > std::chrono::duration<Rep, Period>::zero());
0027 if (!active_)
0028 {
0029 return;
0030 }
0031
0032 worker_thread_ = std::thread([this, callback_fun, interval]() {
0033 for (;;)
0034 {
0035 std::unique_lock<std::mutex> lock(this->mutex_);
0036 if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
0037 {
0038 return;
0039 }
0040 callback_fun();
0041 }
0042 });
0043 }
0044 periodic_worker(const periodic_worker &) = delete;
0045 periodic_worker &operator=(const periodic_worker &) = delete;
0046
0047 ~periodic_worker();
0048
0049 private:
0050 bool active_;
0051 std::thread worker_thread_;
0052 std::mutex mutex_;
0053 std::condition_variable cv_;
0054 };
0055 }
0056 }
0057
0058 #ifdef SPDLOG_HEADER_ONLY
0059 # include "periodic_worker-inl.h"
0060 #endif