How to use SetTimer API
api, c++, windows
Solution
There are few problems with your program:
- C programs do end when they leave `main()` so there is no time when the timer can occur.
Win32 timers need the message pump (see below) to be working, as they are implemented through `WM_TIMER` message, even when they are not associated with any window, and if you provide function callback.
When you specify a TimerProc callback function, the default window procedure calls the callback function when it processes WM_TIMER. Therefore, you need to dispatch messages in the calling thread, even when you use TimerProc instead of processing WM_TIMER.
Source: MSDN: SetTimer function
The callback function has bad prototype. See http://msdn.microsoft.com/en-us/library/windows/desktop/ms644907%28v=vs.85%29.aspx
void CALLBACK f(HWND hwnd, UINT uMsg, UINT timerId, DWORD dwTime)
{
printf("Hello");
}
int main()
{
MSG msg;
SetTimer(NULL, 0, 1000*60,(TIMERPROC) &f);
while(GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
(Note this example program never ends, instead, real program should have some additional logic to do so by sending `WM_QUIT`).
Problem
I tried to use `SetTimer` API to call a function every X minutes. So, i have written this test code ``` void f() { printf("Hello"); } int main() { SetTimer(NULL, 0, 1000*60,(TIMERPROC) &f); } ``` I should have Hello written every minute but it does not work.