设定初始时间,定期增加程序运行时间,时间到后输出stop打印。
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
class Timer {
private:
std::chrono::steady_clock::time_point target_time;
bool active;
std::mutex mtx;
std::condition_variable cv;
std::thread worker;
bool stop_triggered;
long last_seconds; // 用于记录上次打印的秒数,避免重复打印
void worker_thread() {
std::unique_lock<std::mutex> lock(mtx);
while (active) {
// 计算剩余秒数
auto now = std::chrono::steady_clock::now();//系统启动时间
auto remaining = target_time - now;
auto remaining_sec = std::chrono::duration_cast<std::chrono::seconds>(remaining);
long seconds = remaining_sec.count();
// 打印变化后的剩余秒数
if (seconds != last_seconds && seconds >= 0) {
std::cout << "Remaining: " << seconds << " seconds" << std::endl;
last_seconds = seconds;
}
// 检查是否到达设定时间
if (remaining.count() <= 0) {
if (!stop_triggered) {
std::cout << "stop" << std::endl;
stop_triggered = true;
active = false;
}
break;
}
// 智能等待策略
if (seconds > 5) {
// 如果剩余时间超过5秒,每秒检查一次
cv.wait_for(lock, std::chrono::seconds(1));
} else if (seconds > 0) {
// 最后5秒,每半秒检查一次
cv.wait_for(lock, std::chrono::milliseconds(500));
} else {
// 小于0时立即再次检查
cv.wait_for(lock, std::chrono::milliseconds(100));
}
}
}
public:
// 构造函数
Timer(int seconds) : active(true), stop_triggered(false), last_seconds(-1) {
set_time(seconds);
worker = std::thread([this] { worker_thread(); });
worker.detach(); // 使用detach避免在析构时等待
}
// 析构函数
~Timer() {
std::lock_guard<std::mutex> lock(mtx);
active = false;
cv.notify_all();
}
// 设置新目标时间(秒)
void set_time(int seconds) {
std::lock_guard<std::mutex> lock(mtx);
target_time = std::chrono::steady_clock::now() + std::chrono::seconds(seconds);
active = true;
stop_triggered = false;
last_seconds = -1; // 重置上次记录的秒数
cv.notify_all();
}
// 延长当前目标时间(秒)
void add_time(int seconds) {
std::lock_guard<std::mutex> lock(mtx);
if (!active || stop_triggered) return;
target_time += std::chrono::seconds(seconds);
cv.notify_all();
}
};
// 测试代码
int main() {
std::cout << "Starting timer for 5 seconds..." << std::endl;
Timer timer(5); // 初始设定5秒
// 3秒后延长3秒
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Adding 3 seconds..." << std::endl;
timer.add_time(3); // 延长3秒(变成8秒)
// 再等2秒后延长5秒
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Adding 5 seconds..." << std::endl;
timer.add_time(5); // 延长5秒(变成11秒)
// 等待结束
std::this_thread::sleep_for(std::chrono::seconds(12));
return 0;
}