From 1acefc35419fe0143254dc26739bafcb494171cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=BB=E9=AD=82=E5=9C=A3=E4=BD=BF?= Date: Tue, 23 Jan 2024 18:14:11 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0startOne=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Timer.h | 11 +++++++++-- src/Timer.cpp | 22 ++++++++++++++++++++-- 2 files changed, 29 insertions(+), 4 deletions(-) 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