|On this page…|
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:
You use the timer function to create a timer object.
You use timer object properties to specify this information. To learn about all the properties supported by the timer object, see timer and set. You can also set timer object properties when you create them, in step 1.
After you are finished using a timer object, you should delete it from memory. See delete for more information.
Note 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. The drawnow function flushes the event queue.
The following example sets up a timer object that executes a MATLAB command string after 10 seconds elapse. The example creates a timer object, specifying the values of two timer object properties, TimerFcn and StartDelay. TimerFcn specifies the timer callback function. This is the MATLAB command string 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 MATLAB disp command. The StartDelay property specifies how much time elapses before the timer fires.
After creating the timer object, the example uses the start 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.