添加startOne方法

This commit is contained in:
2024-01-23 18:14:11 +08:00
parent 782e17f05a
commit 1acefc3541
2 changed files with 29 additions and 4 deletions

View File

@@ -37,6 +37,7 @@ namespace ling {
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;
@@ -57,14 +58,18 @@ namespace ling {
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->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->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;
/// 设置任务执行器

View File

@@ -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<std::mutex> 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<std::mutex> 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