Skip to content

Instantly share code, notes, and snippets.

@pedro-w
Created December 7, 2020 16:34
Show Gist options
  • Save pedro-w/7877c38c9b5a638c8d807bc3dd2e8fa9 to your computer and use it in GitHub Desktop.
Save pedro-w/7877c38c9b5a638c8d807bc3dd2e8fa9 to your computer and use it in GitHub Desktop.
Experiment with Waitable Timer
#include <Windows.h>
#include <iostream>
std::ostream& printnow() {
static ULONGLONG initial = 0;
if (initial == 0) {
initial = GetTickCount64();
return std::cout << 0 << '\t';
}
else {
return std::cout << (GetTickCount64() - initial) << '\t';
}
}
static const DWORD TIMEOUT = 20000; // Give up after 20s
int main()
{
printnow() << "Start" << std::endl;
HANDLE timer = CreateWaitableTimer(NULL, false, NULL);
if (timer) {
int ticks = 10;
LARGE_INTEGER due_time;
due_time.QuadPart = (LONGLONG)-13 * (LONGLONG)10000000; // thirteen seconds into the future
LONG period = 1000; // every second
SetWaitableTimer(timer, &due_time, period, NULL, NULL, FALSE);
while (ticks > 0) {
int rc = WaitForSingleObject(timer, TIMEOUT);
if (rc == WAIT_TIMEOUT) {
std::cout << "Time out, give up" << std::endl;
ticks = 0;
}
printnow() << "Fire " << ticks << std::endl;
--ticks;
}
CloseHandle(timer);
}
printnow() << "End" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment