From 54b3fff5a84002bbcdfe7340587d4668822ca16e Mon Sep 17 00:00:00 2001 From: abin Date: Fri, 18 Sep 2026 00:18:49 +0800 Subject: [PATCH] example: add timer trigger usage --- examples/CMakeLists.txt | 3 +++ examples/timer_trigger.cpp | 51 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 examples/timer_trigger.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 78840c8..752db61 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -15,3 +15,6 @@ target_link_libraries(timer_callable PRIVATE simple_timer) add_executable(timer_task_error timer_task_error.cpp) target_link_libraries(timer_task_error PRIVATE simple_timer) + +add_executable(timer_trigger timer_trigger.cpp) +target_link_libraries(timer_trigger PRIVATE simple_timer) diff --git a/examples/timer_trigger.cpp b/examples/timer_trigger.cpp new file mode 100644 index 0000000..0ececa6 --- /dev/null +++ b/examples/timer_trigger.cpp @@ -0,0 +1,51 @@ +#include + +#include +#include +#include +#include +#include + +std::int64_t current_time_ms() +{ + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); +} + +int main() +{ + // 回调函数运行在定时器线程中,使用原子计数器统计执行次数。 + std::atomic executions{0}; + + // 创建一个周期为 2 秒的定时器。 + SimpleTimer timer(std::chrono::seconds(2)); + + // 启动定时器。任务会在定时到期,或调用 trigger() 时执行。 + timer.start([&executions]() { + const int execution = ++executions; + std::cout << "[" << current_time_ms() << " ms] Task executed #" << execution << " on thread " + << std::this_thread::get_id() << '\n'; + }); + + std::cout << "Timer started; the scheduled interval is 2 seconds.\n"; + + // 等待一小段时间;还没到 2 秒的周期,不会有定时执行。 + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + std::cout << "Calling trigger() once: task should run immediately.\n"; + // 手动请求执行一次。trigger() 只负责排队,实际任务仍由定时器线程异步执行。 + timer.trigger(); + + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + std::cout << "Calling trigger() twice: both requests are queued.\n"; + // 连续调用两次会产生两个待执行请求,不会合并成一次。 + timer.trigger(); + timer.trigger(); + + // 继续等待,以便观察手动触发和后续周期触发的输出。 + std::this_thread::sleep_for(std::chrono::seconds(7)); + // stop() 会等待正在执行的任务结束,并停止定时器线程。 + timer.stop(); + std::cout << "Timer stopped after " << executions.load() << " executions.\n"; + + return 0; +}