It is possible to emulate a simple timer with a while-loop as I outline below.
The timer object causes me trouble and now I think a construct based on a while-loop would serve better in my specific case. I need a timer that runs "forever" and invokes a "callback function" every few seconds. It should be able to recover after run-time errors in the "callback function".
Reasons to use a while-loop:
- easy to debug; no spurious callbacks
- better error messages; no lost function names and line numbers
- straight forward to catch run-time errors at the top-level with try-catch-end
Reasons to use the timer:
- "The advantage of the timer is it allows you to do something else while the timer is waiting giving you the appearance of multi-threading." copied from Daniels answer.
- better control over when callbacks are fired (see Daniels answer)
- less and more readable code
Have I missed something important?
Out-line of simple "timer" based on a while-loop
period = 1;tasks2execute = 1;TasksToExecute = 3;start_delay = 0;pause( start_delay )while tasks2execute <= TasksToExecutetrytimer_function( ... )catch medisp( 'cleanup' )endpause( period )tasks2execute = tasks2execute + 1;end
and my timer construct; "my specific case" (added 2013-02-09)
tmr = timer('Name' , 'my_timer' ..., 'TimerFcn' , @timer_function ..., 'BusyMode' , 'drop' ..., 'ExecutionMode' , 'fixedDelay' ..., 'Period' , 1 ..., 'StartDelay' , 1 ..., 'TasksToExecute', 999999 ...);start( tmr )wait ( tmr )