I need to create Timer in my VC++ application , at where i need to set timer and on timeout of timer , i need to call one specific method...
i have seen msdn forums for that and done below code to do that
SetTimer(NULL,1,5*1000,TimerProc);
and my TimerProc
method is as below
void CALLBACK TimerProc(HWND aHwnd, UINT aMessage, UINT_PTR aTimerId, DWORD aTime)
{
StopProceess();
}
i assume after 5 seconds the SetTimer
should call TimerProc
method , but it is never called. no idea what i am doing wrong in this. or plz suggest if there's any alternative to do it.
Thanks.
Use waitable timer. Callback will be called after time set by 5-th parameter and repeat every 6-th parameter.
After time elapses, callback is called, executes some processing and sets event to allow exit
// ConsoleTimer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#define TIME_LAPS 5 * 1000
HANDLE g_hExitEvent = NULL;
void CALLBACK WaitOrTimerCallback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
Sleep(5000); // fake long processing
SetEvent(g_hExitEvent);
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hNewTimer = NULL; //call after
BOOL IsCreated = CreateTimerQueueTimer(&hNewTimer, NULL, WaitOrTimerCallback, NULL, TIME_LAPS,
// repeat
TIME_LAPS, WT_EXECUTELONGFUNCTION);
g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
WaitForSingleObject(g_hExitEvent, 15000);
DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
return 0;
}
I do not check for errors, you should.
From the code snippet I am pretty sure you are writing console based application.
You can use other type of timers or if you are not really concern about precision there is one thing you missed in order to make this timer to work.
Even though this is a console app, your timer callback will not be called unless you dispatch timer message.
Do this:
MSG msg;
SetTimer(NULL, 1, 5*1000 ,TimerProc);
while (GetMessage(&msg, NULL, WM_NULL, WM_TIMER))
{
DispatchMessage(&msg);
if (WM_TIMER == msg.message)
{
break;
}
}
StopProceess();
Consider using Waitable Timer.
Well, it looks ok to me. Have you set breakpoints in your program in the TimerProc and where you call SetTimer? You need to be sure you really call SetTimer and that TimerProc is not really being called.
The next thing I would ask is whether you are dispatching messages in a message loop? If you aren't dispatching messages in a message loop, I don't think the timer message will never get fired. If you execute some long process in your program and you are never calling GetMessage/PeakMessage with a corresponding DispatchMessage then this might cause the timer message never to get fired.
This article goes through creating and destroying a timer.
I found some example code, which still uses a hWnd, is there any reason why you don't use a hWnd parameter? If you can't use one, you can try and see if the code works when you pass in NULL. I have noticed in the examples they cast the callback to a TIMERPROC
.