Reputation: 17313
Say, I have the following C++ code.
First I create a manual waitable timer as such:
HANDLE hWTimer = CreateWaitableTimer(NULL, FALSE, NULL);
Then it's set to a predefined time in the future to fire once (the actual value is provided by a user input):
double fSeconds2Wait = 10000;
LARGE_INTEGER li;
//Convert to 100 nanosecond intervals (MUST BE NEGATIVE)
li.QuadPart = -10000000LL * (LONGLONG)fSeconds2Wait;
SetWaitableTimer(hWTimer, &li, 0, NULL, NULL, 0);
Then I have a worker thread that resides in a waiting state, waiting for the timer to fire:
WaitForSingleObject(hWTimer, INFINITE);
//Perform actions when timer fires
The question I have, say, if I want to hold off the 'hWTimer' indefinitely with a possibility to reset it to another time later (upon user request), how do I do that?
Upvotes: 3
Views: 1504
Reputation: 2474
from MSDN Docs
For SetWaitableTimer
Timers are initially inactive. To activate a timer, call SetWaitableTimer. If the timer is already active when you call SetWaitableTimer, the timer is stopped, then it is reactivated. Stopping the timer in this manner does not set the timer state to signaled, so threads blocked in a wait operation on the timer remain blocked. However, it does cancel any pending completion routines.
and For CancelWaitableTimer
The CancelWaitableTimer function does not change the signaled state of the timer. It stops the timer before it can be set to the signaled state and cancels outstanding APCs. Therefore, threads performing a wait operation on the timer remain waiting until they time out or the timer is reactivated and its state is set to signaled. If the timer is already in the signaled state, it remains in that state.
To reactivate the timer, call the SetWaitableTimer function.
So from this you can hold off your timer (and thread) by calling CancelWaitableTimer, and on request from the user, restart it by calling SetWaitableTimer.
Upvotes: 1