From: Bertel Brander on
Dave skrev:
> Certainly, thanks for the help!
>
> I have an application that itself owns numerous classes. I'm
> implementing a state pattern, where each class is a state. These
> state objects are owned in turn by a state manager, who is
> instantiated by main.
>
> Some events cause timers to start. When some timers expire they cause
> state transitions. Sometimes I will need to stop the timers early.
> Other times I'll need to 'tick' a value and reschedule them.
>
> Is there any way I can simply specify a function handler to be called
> when the timer expires? I really don't want to have to have my main
> handle all possible timer events as they are elements of the states
> and not main.

You could do:
#include <windows.h>
#include <iostream>

class TimerBase
{
public:
virtual void OnTimer() = 0;
};

class X : public TimerBase
{
public:
void OnTimer()
{
std::cout << "X::OnTimer" << std::endl;
}
};

class Y : public TimerBase
{
public:
void OnTimer()
{
std::cout << "Y::OnTimer" << std::endl;
}
};

int main()
{
X x;
Y y;
SetTimer(0, 1024, 1000, (TIMERPROC )&x);
SetTimer(0, 1024, 750, (TIMERPROC )&y);
MSG Message;
while(GetMessage(&Message, 0, 0, 0))
{
if(Message.message == WM_TIMER)
{
TimerBase* ptr = (TimerBase *)Message.lParam;
ptr->OnTimer();
}
}
}

You could spawn a seperate thread to run the message loop,
but that would requere synchronization between the threads.

--
Just another homepage:
http://damb.dk
But it's mine - Bertel
From: PJ Naughter on
On 31 Jan 2007 14:43:53 -0800, "Dave" <davechandler(a)gmail.com> wrote:

>I'm having trouble figuring out how to create and use a timer in
>Windows when you don't want to build an actual windowed application,
>but rather are making a console app. All examples I've found so tie
>timers directly into the windows.
>
>For Example:
>
>http://msdn2.microsoft.com/en-us/library/microsoft.win32.systemevents.createtimer(VS.80).aspx
>
>Any suggestions?
>
>PS I am NOT using dot net

Unless you are running a message pump loop in your console application
i.e. GetMessage / Translate / Dispatchmessage which is not too common,
you would probably be best to use waitable timers in conjuction with a
WaitForMultipleObjects call. If you are interested there is a MFC
wrapper for waitable timers on my web site at
http://www.naughter.com/waitabletimer.html.

Regards,
PJ Naughter

Naughter Software
Mail: pjna at naughter.com
Web: www.naughter.com
Hotmail/MSN Messenger: pjnaughter at hotmail.com

It is finally on the shelves... the book from Joseph Gama and I:

http://www.amazon.com/Super-SQL-Server-Systems-Performance/dp/0976157322