For a Windows Service, I need a timer to perform a certain task regularly. Of course, there are many options that seem superior to a timer (multithreading, calling method directly from the service's main thread), but they all have their disadvantages in this particular situation.
However, for obvious reasons, SetTimer() does not work without the message queue of a GUI. What I have done (in Free Pascal) is the following:
Create the timer:
MyTimerID := SetTimer(0, 0, 3333, @MyTimerProc);
In the main loop of the service, run the timer queue:
procedure TMyServiceThread.Execute;
var
AMessage: TMsg;
begin
repeat
// Some calls
if PeekMessage(AMessage, -1, WM_TIMER, WM_TIMER, PM_REMOVE) then begin
TranslateMessage(AMessage);
DispatchMessage(AMessage);
end;
// Some more calls
TerminateEventObject.WaitFor(1000);
until Terminated;
end;
And at the end, kill the timer:
KillTimer(0, MyTimerID)
Except of KillTimer always returning False, this works as anticipated.
I am interested in your feedback, however, if my implementation is correct - I just want to avoid messing with other application's messages and other side effects I am not aware of because of my inexperience with message handling.
Thanks!