diff --git a/include/Timer.h b/include/Timer.h index 801ac0a..d5cd8eb 100644 --- a/include/Timer.h +++ b/include/Timer.h @@ -37,6 +37,7 @@ namespace ling { static std::atomic flag; static std::condition_variable listCV; + std::atomic state{true}; std::function recall; int64_t id = 0; Task task; @@ -57,14 +58,18 @@ namespace ling { 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->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->recall(); }; this->task.time = std::time(nullptr) + this->task.interval; this->task.fun = warpper_func; @@ -82,6 +87,8 @@ namespace ling { /// 重新启动定时器 void start(); + void startOne(int64_t interval); + void stop() const; /// 设置任务执行器 diff --git a/src/Timer.cpp b/src/Timer.cpp index d7dfa5c..f26dc53 100644 --- a/src/Timer.cpp +++ b/src/Timer.cpp @@ -32,8 +32,8 @@ namespace ling { Task task = list.front(); std::time_t time = std::time(nullptr); if (task.time <= time) { - call(task.fun); list.pop_front(); + call(task.fun); continue; } } @@ -76,6 +76,7 @@ namespace ling { } void Timer::start(int64_t interval) { + this->state.store(true); { std::unique_lock lock(mutex); for (auto it = list.begin(); it != list.end(); ++it) { @@ -101,6 +102,24 @@ namespace ling { } } + void Timer::startOne(int64_t interval) { + this->state.store(false); + { + std::unique_lock lock(mutex); + for (auto it = list.begin(); it != list.end(); ++it) { + if (it->id == this->id) { + list.erase(it); + break; + } + } + } + + this->task.time = std::time(nullptr) + interval; + this->task.interval = interval; + addTask(task); + } + + void Timer::start() { start(this->task.interval); } @@ -108,5 +127,4 @@ namespace ling { Timer::~Timer() { stop(); } - } // ling \ No newline at end of file