#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
std::atomic<bool> stop_thread(false); // 用于控制线程的停止
// 定时任务函数,每隔 3 秒执行一次
void periodic_task() {
while (!stop_thread) {
std::this_thread::sleep_for(std::chrono::seconds(3)); // 等待 3 秒
std::cout << "定时任务执行了!" << std::endl;
}
}
int main() {
std::cout << "主程序开始..." << std::endl;
// 启动后台线程来执行定时任务
std::thread timer_thread(periodic_task);
// 主程序继续做其他事情
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1)); // 每隔 1 秒输出一次
std::cout << "主线程正在运行..." << std::endl;
}
// 等待后台线程结束
timer_thread.join();
// 停止定时任务
//stop_thread = true;
std::cout << "主程序结束..." << std::endl;
return 0;
}
定时器-后台执行----c++
最新推荐文章于 2025-01-14 15:16:16 发布