Schedule Command Execution Using Timer
The MATLAB® software includes a timer object that you can use to schedule the execution of MATLAB commands. This section describes how you can create timer objects, start a timer running, and specify the processing that you want performed when a timer fires. A timer is said to fire when the amount of time specified by the timer object elapses and the timer object executes the commands you specify.
To use a timer, perform these steps:
Create a timer object.
You use the
timerfunction to create a timer object.
Specify which MATLAB commands you want executed when the timer fires and control other aspects of timer object behavior.
You use timer object properties to specify this information. To learn about all the properties supported by the timer object, see
timer. You can also set timer object properties when you create them, in step 1.
Start the timer object.
Delete the timer object when you are done with it.
After you are finished using a timer object, you should delete it from memory. See
deletefor more information.
The specified execution time and the actual execution of a timer can vary
because timer objects work in the MATLAB single-threaded execution environment. The length of this time lag
is dependent on what other processing MATLAB is performing. To force the execution of the callback functions in
the event queue, include a call to the
drawnow function in your code.
drawnow function flushes the event queue.
Example: Displaying a Message
The following example sets up a timer object that executes a MATLAB command character vector after 10 seconds elapse. The example creates
a timer object, specifying the values of two timer object properties,
TimerFcn specifies the timer callback function. This is the
MATLAB command or program file that you want to execute when the timer fires.
In the example, the timer callback function sets the value of the MATLAB workspace variable
stat and executes the
disp command. The
specifies how much time elapses before the timer fires.
After creating the timer object, the example uses the
function to start the timer object. (The additional commands in this example are
included to illustrate the timer but are not required for timer operation.)
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',... 'StartDelay',10); start(t) stat=true; while(stat==true) disp('.') pause(1) end
When you execute this code, it produces this output:
. . . . . . . . . Timer! delete(t) % Always delete timer objects after using them.