在無作業系統排程器 (如 Linux cron、Windows Task Scheduler) 的環境下,用純 C++ 標準庫實現「每隔 1 秒執行一次邏輯」。
#include <iostream>
#include <ctime>
int getSeconds() {
return static_cast(std::clock() / CLOCKS_PER_SEC);
}
int main() {
int counter = 0;
int lastSec = getSeconds();
while (true) {
int now = getSeconds();
if (now - lastSec >= 1) {
std::cout << "Tick " << ++counter << " @ " << now << "s" << std::endl;
lastSec = now;
}
// 注意:這是忙等待 (Busy-wait),CPU 佔用 100%
}
return 0;
}
缺點: 空轉燒 CPU、clock() 精度依賴實現 (通常 1ms~10ms)、無法應對系統時間調整。
#include <iostream>
#include <chrono>
#include <thread>
int main() {
using namespace std::chrono_literals;
int counter = 0;
auto next = std::chrono::steady_clock::now();
while (true) {
next += 1s; // 目標下一個整秒時間點
std::this_thread::sleep_until(next); // 睡眠至目標時間點
std::cout << "Tick " << ++counter << std::endl;
// 執行任務邏輯...
}
}
優點: 釋放 CPU、steady_clock 單調不受系統時間調整影響、自動補償任務執行時間漂移 (若任務耗時 < 1s)。
#include <chrono>
#include <thread>
#include <atomic>
#include <functional>
#include <iostream>
class PeriodicTask {
public:
using Clock = std::chrono::steady_clock;
using Duration = std::chrono::milliseconds;
explicit PeriodicTask(Duration interval, std::function task)
: interval_(interval), task_(std::move(task)), running_(false) {}
void start() {
running_ = true;
thread_ = std::thread([this] { runLoop(); });
}
void stop() {
running_ = false;
if (thread_.joinable()) thread_.join();
}
~PeriodicTask() { stop(); }
private:
void runLoop() {
auto next = Clock::now();
while (running_) {
next += interval_;
task_(); // 執行用戶任務
auto now = Clock::now();
if (next > now) {
std::this_thread::sleep_until(next);
} else {
// 任務耗時超過間隔:立即執行下一次 (或記錄警告、跳過)
next = now;
}
}
}
Duration interval_;
std::function task_;
std::atomic running_;
std::thread thread_;
};
// 使用範例
int main() {
PeriodicTask task(1000ms, []{ std::cout << "心跳 @" << std::time(nullptr) << std::endl; });
task.start();
std::this_thread::sleep_for(10s);
task.stop();
return 0;
}
| 議題 | 處理方式 |
|---|---|
| 時鐘選擇 | steady_clock:單調、不受 NTP/手動調整時間影響 |
| 漂移補償 | sleep_until 針對固定時間點睡眠,而非固定時長,避免累積誤差 |
| 任務超時 | 若任務耗時 > 間隔,選擇「立即重跑」或「跳過本輪」或「並行執行」 |
| 優雅停止 | atomic + join() 確保線程安全退出 |
| 精度 | 毫秒級;微秒級需 timerfd (Linux) / CreateTimerQueueTimer (Windows) |
現代 C++ (C++11 起) 配合 <chrono> 和 <thread>,能寫出可移植、高精度、低 CPU 佔用的週期任務。**拒絕忙等待,擁抱 sleep_until**,並將週期邏輯封裝為可複用元件,是專業 C++ 開發者的基本功。