// // Created by ling on 24-1-23. // #ifndef TIMER_TIMER_H #define TIMER_TIMER_H #include #include #include #include #include #include #include #include namespace ling { /// 低精度定时器,最大时间粒度为秒 class Timer { private: struct Task { std::time_t time; int64_t interval; std::function fun; int64_t id; void operator()(); }; //执行函数,可以用来结合线程池使用 static std::function fun)> call; static int64_t nextId; static std::mutex mutex; static std::list list; static std::thread thread; static std::atomic flag; static std::condition_variable listCV; std::atomic state{true}; std::function recall; int64_t id = 0; Task task; protected: static void addTask(const Task &task); public: explicit Timer() { this->id = nextId++; } template Timer &bind(F &&f, Args &&...args) { std::function func = std::bind(std::forward(f), std::forward( args)...); // 连接函数和参数定义,特殊函数类型,避免左右值错误 auto task_ptr = std::make_shared>(func); std::function warpper_func = [task_ptr, this]() { if (this->state.load()) { this->recall(); } (*task_ptr)(); }; this->recall = [this, func]() { auto task_ptr = std::make_shared>(func); std::function warpper_func = [task_ptr, this]() { if (this->state.load()) { this->recall(); } (*task_ptr)(); }; this->task.time = std::time(nullptr) + this->task.interval; this->task.fun = warpper_func; addTask(task); }; task.fun = warpper_func; task.id = this->id; return *this; } template static void startTask(F &&f, int64_t interval, Args &&...args) { std::function func = std::bind(std::forward(f), std::forward( args)...); // 连接函数和参数定义,特殊函数类型,避免左右值错误 auto task_ptr = std::make_shared>(func); std::function warpper_func = [task_ptr]() { (*task_ptr)(); }; Task task; task.id = -1; task.time = std::time(nullptr) + interval; task.fun = warpper_func; addTask(task); } /// 启动定时器 void start(int64_t interval); /// 重新启动定时器 void start(); void startOne(int64_t interval); void stop() const; /// 设置任务执行器 static void setCall(const std::function)> &call); /// 立即停止定时器,没有执行的任务将全部丢弃 static void stopAll(); virtual ~Timer(); }; } // ling #endif //TIMER_TIMER_H