在C++中实现定时功能可以使用系统提供的时间库或者第三方库来实现。以下是使用C++11标准库中的<chrono>和<thread>来实现定时功能的示例代码:
#include <iostream>#include <thread>#include <chrono>void timer_function(){ std::cout << "Timer function called at: " << std::chrono::system_clock::now() << std::endl;}int main(){ // 设置定时器间隔 std::chrono::seconds interval(1); // 创建定时器循环 while (true) { // 调用定时函数 timer_function(); // 等待指定时间 std::this_thread::sleep_for(interval); } return 0;}在上面的示例中,timer_function函数会被定时调用,每隔1秒输出当前时间。这里使用了std::chrono::system_clock::now()来获取当前时间,并使用std::this_thread::sleep_for(interval)来实现定时功能。
另外,如果需要更复杂的定时功能,也可以考虑使用第三方库,例如Boost库中的定时器功能。


