0
点赞
收藏
分享

微信扫一扫

Timer 定时器

飞进科技 2022-03-24 阅读 143
windowsc++

Windows 上原生Timer常用的有下面两个:

1. SetTimer windows上最简单方便的定时器,不足之处是要依赖消息循环,不能在工作线程使用。时钟到了会将WM_TIMER放入消息队列,也会收到消息队列中消息数量和消息处理过程影响

2. SetWaitableTimer 内核定时器,可以在任何线程使用。精度也较SetTimer高,不过对不同系统这个默认精度不同,可以通过timeBeginPeriod设置,这个在msdn SetWaitableTimer 的介绍中也有提到:SetWaitableTimer function (synchapi.h) - Win32 apps | Microsoft DocsActivates the specified waitable timer. When the due time arrives, the timer is signaled and the thread that set the timer calls the optional completion routine.icon-default.png?t=M276https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-setwaitabletimer

 通过超时机制自定义timer:

上面是 windows 原生定时器,也可以通过超时机制自己构建一个定时器,比如windows 上可以利用Sleep/WaitForSingleObject等支持超时的函数,配合循环完成一个自制的定时器。

跨平台的方案也有,比如boost::asio中就有定时器支持。也可以利用std::this_thread::sleep_for \ std::condition_variable的wait_for超时,socket的select超时,来实现自定义定时器。

举报

相关推荐

0 条评论