如何用C++23在一天的特定时间调用函数?
C++23实现每日特定时间触发函数的简洁方案
针对你需要在每日16:00和22:00触发函数、且首次需等待到下一个目标时间点的需求,利用C++23的<chrono>库可以实现高效且简洁的方案,核心思路是基于系统时钟计算下一个触发时间点,通过sleep_until阻塞等待,避免空轮询浪费资源。
实现代码
#include <chrono> #include <thread> #include <iostream> void call_function() { std::cout << "函数执行于: " << std::chrono::system_clock::now() << '\n'; } int main() { using namespace std::chrono; // 定义每日触发的时间点(仅时间部分,以午夜为起点的时长表示) constexpr auto target_16h = hours(16); constexpr auto target_22h = hours(22); while (true) { // 获取当前系统时间 const auto now = system_clock::now(); // 提取当天已过的时长(即当前时间相对于午夜的偏移) const auto time_since_midnight = make_day_time(now).time_since_midnight(); // 计算下一个触发的系统时间点 sys_time<seconds> next_trigger; const auto today_start = floor<days>(now); if (time_since_midnight < target_16h) { next_trigger = today_start + target_16h; } else if (time_since_midnight < target_22h) { next_trigger = today_start + target_22h; } else { // 当前时间晚于22:00,等待次日16:00 next_trigger = today_start + days(1) + target_16h; } // 阻塞等待到触发时间 std::this_thread::sleep_until(next_trigger); // 执行目标函数 call_function(); } }
关键细节说明
时间对象的提取:
使用C++23新增的make_day_time(now)可以直接获取包含日期和当日时间的对象,调用time_since_midnight()得到当前时间相对于午夜的时长(即你需要的“仅时间对象”),无需关注具体日期。下一个触发时间计算:
通过比较当日已过时长久与目标时长(16小时、22小时),判断下一个触发点是当天的16:00、22:00,还是次日的16:00,完全符合你的需求。高效等待机制:
std::this_thread::sleep_until会让线程阻塞到指定的系统时间点,相比循环查询当前时间的方式,大幅降低CPU占用,且能自动适配系统时间调整(如夏令时、手动修改时间)。精度控制:
示例中使用sys_time<seconds>将时间精度控制到秒,若需要更高精度(如毫秒),只需将seconds替换为milliseconds或microseconds即可。
内容的提问来源于stack exchange,提问作者intrigued_66
相关产品推荐
相关产品推荐

