Using a MATLAB® Timer Object

Overview

The MATLAB® softwareincludes 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:

  1. Create a timer object.

    You use the timer function to create a timer object. See Creating Timer Objects for more information.

  2. 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 Working with Timer Object Properties. (You can also set timer object properties when you create them, in step 1.)

  3. Start the timer object.

    After you create the timer object, you must start it, using either the start or startat function. See Starting and Stopping Timers for more information.

  4. 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 Deleting Timer Objects from Memory for more information.

Example: Displaying a Message

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 M-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.
  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS