Does the Windows native API support timers?
I am aware that POSIX implementations on Windows support tim开发者_Python百科ers, but I am interested in Windows SDK APIs.
Yes there are timers in Win32 API. More details you can check here : Timers
In particular you need to check
- SetTimer
- KillTimer
- TimerProc
- WM_TIMER
It sure does: http://windows-programming.suite101.com/article.cfm/using_the_win32_timer_api
The SetTimer
API mentioned in that article depends on the WM_TIMER
message, which means that you have to have a message loop, which means that you (probably) have to have a window. So it's very useful for GUI programming, less so for command-line tools.
In addition to the timers described above there is also the high-resolution timeSetEvent
(Multimedia API) & CreateTimerQueueTimer
.
It's a tricky question to answer in the context of a POSIX timer. The Window API SetTimer creates a timer on a GUI thread that relies on the thread's message queue dispatching mechanism - which means somewhere in the thread you are calling GetMessage / DispatchMessage.
If you are writing non-GUI code, having to implement a message loop is an unnatural constraint :- The Windows kernel uses synchronization objects (in place of signals) as a way for worker (i.e. non-GUI) threads to be alerted to events. CreateWaitiableTimer will create a handle that can be passed to WaitForSingleObject / WaitForMultipleObjects in a worker thread.
Alternately, you can create a worker thread - implement a timer (GUI or kernel) in that, and simply call into your (obviously, it must be a thread-safe) object as the timer is signaled.
The choice really depends on exactly how POSIX-like your application is going to be.
精彩评论