Files
Timer/include/Timer.h
2024-01-23 18:21:02 +08:00

121 lines
3.5 KiB
C++

//
// 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::atomic<bool> state{true};
std::function<void()> recall;
int64_t id = 0;
Task task;
protected:
static void addTask(const Task &task);
public:
explicit Timer() {
this->id = nextId++;
}
template<typename F, typename... Args>
Timer &bind(F &&f, Args &&...args) {
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]() {
if (this->state.load()) {
this->recall();
}
(*task_ptr)();
};
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]() {
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<typename F, typename... Args>
static void startTask(F &&f, int64_t interval, Args &&...args) {
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]() {
(*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<void(std::function<void()>)> &call);
/// 立即停止定时器,没有执行的任务将全部丢弃
static void stopAll();
virtual ~Timer();
};
} // ling
#endif //TIMER_TIMER_H