实现简单定时器

This commit is contained in:
2024-01-23 16:27:37 +08:00
parent 5097161b53
commit ca23184273
4 changed files with 234 additions and 2 deletions

94
include/Timer.h Normal file
View File

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