View Full Version : Best way to call a function every 5 secs

01-31-2011, 06:39 AM
Right now I'm just comparing against the BaseApp ticks in a Component's Update function:

int nTime = GetBaseApp()->GetTick();

// wait 5 seconds
if( (nTime - m_msgTime ) >= 5000 )
// DoSomething();
m_msgTime = nTime;

Is there a better way to do this with boost/your messaging system?

01-31-2011, 08:34 AM
The "componenty" way to do it would be:

Link the function in the component's OnAdd()

GetFunction("DoSomething")->sig_function.connect(1, boost::bind(&MyComponent::DoSomething, this, _1));

//note: you could also link to a non-member function if you want

Make the sure the function actually exists (and add to the .h):

void MyComponent::DoSomething(VariantList *pVList)
LogMsg("Doing something cool");

Schedule the function to be called:

GetMessageManager()->CallComponentFunction(this, 5000, "DoSomething");

And I guess you'd want to also call the above from inside the DoSomething so it keeps calling itself every 5000 ms.

So is it worth doing all that?

Well, I guess it depends what it's for. Doing it this way makes the following possible:

Things outside the class can schedule it to be run
You can easily send in parms, instead of using member variables to store them
You can "overlap" calls, sometimes useful
Other entities/components could also link to this component's DoSomething, to be notified when it happens, possibly to do something additionally
It's possible to schedule a call on a component that doesn't even exist yet.. uh, probably don't need that, but hey.
Don't need a timing variable cluttering up things in your component class

If you don't ever want overlapping calls and that is a danger of happening for some reason, one option is to use MessageManager::DeleteMessagesByFunctionCallName or MessageManager::DeleteMessagesToComponent to kill existing calls in the pipeline.

Reasons you shouldn't use the "entity" way are:

Boost is slow, if you're calling something every few frames, use something else
If multiple places in your code want to check the timing, might as well do your own timer
If you never want to allow overlapping or need complex scheduling, a single uint32 timer is simpler