timer class

Create object to schedule execution of MATLAB commands

Description

Use a timer object to schedule the execution of MATLAB® commands one or multiple times. If you schedule the timer to execute multiple times, you can define the time between executions and how to handle queuing conflicts.

The timer object uses callback functions to execute commands. Callback functions execute code during some event. For the timer object, you can specify the callback function as a function handle or as a character vector. If the callback function is a character vector, MATLAB evaluates it as executable code. The timer object supports callback functions when a timer starts (StartFcn), executes (TimerFcn), stops (StopFcn), or encounters an error (ErrorFcn).

Note

The timer object is subject to the limitations of your hardware, operating system, and software. Avoid using timer objects for real-time applications.

Construction

t = timer creates an empty timer object to schedule execution of MATLAB commands. An error occurs if the timer starts and TimerFcn is not defined.

t = timer(Name,Value) creates a timer object with additional options that you specify using one or more Name,Value pair arguments.

Input Arguments

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

The argument name, Name, corresponds to a timer property name. In the constructor, the property values are specified using Name,Value pair arguments.

'BusyMode'

Character vector or string scalar that indicates action taken when a timer has to execute TimerFcn before the completion of previous execution of the TimerFcn. When Running='on', BusyMode is read only. This table summarizes the busy modes.

BusyMode Values

Behavior if Queue Empty

Behavior if Queue Not Empty

Notes

'drop'

Adds task to queue

Drops task

Possible skipping of TimerFcn calls

'error'

Adds task to queue

Completes task; throws error specified by ErrorFcn; stops timer

Stops timer after completing task in execution queue

'queue'

Adds task to queue

Waits for queue to clear, and then enters task in queue

Adjusts Period property to manage tasks in execution queue

See Handling Timer Queuing Conflicts for more information.

Default: 'drop'

'ErrorFcn'

Character vector, string scalar, function handle, or cell array defining the function that the timer executes when an error occurs. If there is an error, this function executes, and then calls StopFcn.

  • If you specify this property using a character vector or string scalar, when MATLAB executes the callback it evaluates the MATLAB code contained in the character vector.

  • If you specify this property using a function handle, when MATLAB executes the callback it passes the timer object and an event structure to the callback function. The event structure contains the type of event in the Type field and the time of the event in the Data field.

  • If your callback function accepts arguments in addition to the timer object and event data, specify this property as a cell array containing the function handle and the additional arguments.

For more information, see Timer Callback Functions.

'ExecutionMode'

Character vector or string scalar that defines how the timer object schedules timer events. When Running='on', ExecutionMode is read only. This table summarizes the execution modes.

Execution Mode

Time Period Start Point

'singleShot'

In this mode, the timer callback function is only executed once. Therefore, the Period property has no effect. This is the default execution mode.

'fixedRate'

Starts immediately after the timer callback function is added to the MATLAB execution queue

'fixedDelay'

Starts when the timer function callback restarts execution after a time lag due to delays in the MATLAB execution queue

'fixedSpacing'

Starts when the timer callback function finishes executing.

  • 'singleShot' is the single execution mode for the timer class, and is the default value.

  • 'fixedDelay', 'fixedRate', and 'fixedSpacing' are the three supported multiexecution modes. These modes define the starting point of the Period property. The Period property specifies the amount of time between executions, which remains the same. Only the point at which execution begins is different.

Default: 'singleShot'

'Name'

Character vector or string scalar representing the timer name.

Default: 'timer-i', where i is a number indicating the ith timer object created this session. To reset i to 1, execute the clear classes command.

'ObjectVisibility'

Character vector or string scalar with possible values of 'on' or 'off', that provides a way for you to discourage end-user access to the timer objects your application creates. The timerfind function does not return an object whose ObjectVisibility property is set to 'off'. Objects that are not visible are still valid. To retrieve a list of all the timer objects in memory, including the invisible ones, use the timerfindall function.

Default: 'on'

'Period'

Number greater than 0.001 that specifies the delay, in seconds, between executions of TimerFcn. For the timer to use Period, you must set ExecutionMode and TasksToExecute to schedule multiple timer object callback events.

Default: 1.0

'StartDelay'

Number greater than or equal to 0 that specifies the delay, in seconds, between the start of the timer and the first execution of the function specified in TimerFcn. When Running = 'on', StartDelay is read only.

Default: 0

'StartFcn'

Character vector, string scalar, function handle, or cell array defining the function that executes when the timer starts.

  • If you specify this property using a character vector or string scalar, when MATLAB executes the callback it evaluates the MATLAB code contained in the character vector.

  • If you specify this property using a function handle, when MATLAB executes the callback it passes the timer object and an event structure to the callback function. The event structure contains the type of event in the Type field and the time of the event in the Data field.

  • If your callback function accepts arguments in addition to the timer object and event data, specify this property as a cell array containing the function handle and the additional arguments.

For more information, see Timer Callback Functions.

'StopFcn'

Character vector, string scalar, function handle, or cell array defining the function that executes when the timer stops.

  • If you specify this property using a character vector or string scalar, when MATLAB executes the callback it evaluates the MATLAB code contained in the character vector.

  • If you specify this property using a function handle, when MATLAB executes the callback it passes the timer object and an event structure to the callback function. The event structure contains the type of event in the Type field and the time of the event in the Data field.

  • If your callback function accepts arguments in addition to the timer object and event data, specify this property as a cell array containing the function handle and the additional arguments.

For more information, see Timer Callback Functions.

The timer stops when

  • You call the timer stop method.

  • The timer finishes executing TimerFcn. In other words, the value of TasksExecuted reaches the limit set by TasksToExecute.

  • An error occurs. The ErrorFcn callback is called first, followed by the StopFcn callback.

You can use StopFcn to define clean up actions, such as deleting the timer object from memory.

'Tag'

Character vector or string scalar that represents a label for the object.

'TasksToExecute'

Number greater than 0, indicating the number of times the timer object is to execute the TimerFcn callback. Use the TasksToExecute property to set the number of executions. To use TasksToExecute, you must set ExecutionMode to schedule multiple timer callback events.

Default: Inf

'TimerFcn'

Character vector, string scalar, function handle, or cell array defining the timer callback function. You must define this property before you can start the timer.

  • If you specify this property using a character vector or string scalar, when MATLAB executes the callback it evaluates the MATLAB code contained in the character vector.

  • If you specify this property using a function handle, when MATLAB executes the callback it passes the timer object and an event structure to the callback function. The event structure contains the type of event in the Type field and the time of the event in the Data field.

  • If your callback function accepts arguments in addition to the timer object and event data, specify this property as a cell array containing the function handle and the additional arguments.

For more information, see Timer Callback Functions.

'UserData'

Generic field for data that you want to add to the object.

Properties

AveragePeriod

Average time in seconds between TimerFcn executions since the timer started. Value is NaN until timer executes two timer callbacks.

InstantPeriod

The time in seconds between the last two executions of TimerFcn. Value is NaN until timer executes two timer callbacks.

Running

Character vector defined as 'off' or 'on', indicating whether the timer is currently executing callback functions.

TasksExecuted

The number of times the timer called TimerFcn since the timer started.

Type

Character vector that identifies the object type.

Methods

deleteRemove timer object from memory
getQuery property values for timer object
isvalidDetermine timer object validity
setSet property values for timer object
startStart timer object
startatSchedule timer to fire at specified time
stopStop timer object
timerfindFind timer object
timerfindallFind timer object, regardless of visibility
waitBlock command prompt until timer stops running

Copy Semantics

Handle. To learn how handle classes affect copy operations, see Copying Objects.

Examples

collapse all

Display a message using an anonymous function as a callback function. It is important to note that the first two arguments the callback function passes are a handle to the timer object and an event structure. Even if the function doesn't use these arguments, the function definition requires them.

Wait 3 seconds, and then display the message ‘3 seconds have elapsed’.

t = timer;
t.StartDelay = 3;
t.TimerFcn = @(myTimerObj, thisEvent)disp('3 seconds have elapsed');
start(t)
3 seconds have elapsed

Suppose the function does not require the timer or event object. Use the tilde (~) operator to ignore the inputs.

t.TimerFcn = @(~,~) disp('3 seconds have elapsed');
start(t)
3 seconds have elapsed

Delete the timer object.

delete(t)

Display the event and date/time output when the timer starts, fires, and stops. The timer callback function will be executed 3 times with 2 seconds between calls. The first two arguments the callback function passes are a handle to the timer object and an event structure. The event structure contains two fields: Type is a character vector that identifies the type of event that caused the callback, and Data is a structure that contains a date time vector of when the event occurred.

t = timer;
t.StartFcn = @(~,thisEvent)disp([thisEvent.Type ' executed '...
    datestr(thisEvent.Data.time,'dd-mmm-yyyy HH:MM:SS.FFF')]);
t.TimerFcn = @(~,thisEvent)disp([thisEvent.Type ' executed '...
     datestr(thisEvent.Data.time,'dd-mmm-yyyy HH:MM:SS.FFF')]);
t.StopFcn = @(~,thisEvent)disp([thisEvent.Type ' executed '...
    datestr(thisEvent.Data.time,'dd-mmm-yyyy HH:MM:SS.FFF')]);
t.Period = 2;
t.TasksToExecute = 3;
t.ExecutionMode = 'fixedRate';
start(t)
StartFcn executed 14-Mar-2013 09:08:50.865
TimerFcn executed 14-Mar-2013 09:08:50.865
TimerFcn executed 14-Mar-2013 09:08:52.865
TimerFcn executed 14-Mar-2013 09:08:54.866
StopFcn executed 14-Mar-2013 09:08:54.869

Delete the timer object.

delete(t)

Create a timer object to remind yourself to take 30-second ergonomic breaks every 10 minutes over the course of 8 hours.

Create a function in a file named createErgoTimer.m that returns a timer object. Have this file include three local functions to handle timer start, execute, and stop tasks.

function t = createErgoTimer()
secondsBreak = 30;
secondsBreakInterval = 600;
secondsPerHour = 60^2;
secondsWorkTime = 8*secondsPerHour;

t = timer;
t.UserData = secondsBreak;
t.StartFcn = @ergoTimerStart;
t.TimerFcn = @takeBreak;
t.StopFcn = @ergoTimerCleanup;
t.Period = secondsBreakInterval+secondsBreak;
t.StartDelay = t.Period-secondsBreak;
t.TasksToExecute = ceil(secondsWorkTime/t.Period);
t.ExecutionMode = 'fixedSpacing';
end 

Using StartDelay allows the timer to start without directing you to take a break immediately. Set the execution mode to 'fixedSpacing' so that 10 minutes and 30 seconds (t.Period) elapses after the completion of a TimerFcn execution. This allows you to stretch for 30 seconds before the start of the next 10 minute interval.

In the createErgoTimer.m file, add a local function to handle the tasks associated with starting the timer. By default, the timer object passes itself and event data to the callback function. The function disregards the event data.

function ergoTimerStart(mTimer,~)
secondsPerMinute = 60;
secondsPerHour = 60*secondsPerMinute;
str1 = 'Starting Ergonomic Break Timer.  ';
str2 = sprintf('For the next %d hours you will be notified',...
    round(mTimer.TasksToExecute*(mTimer.Period + ...
    mTimer.UserData)/secondsPerHour));
str3 = sprintf(' to take a %d second break every %d minutes.',...
    mTimer.UserData, (mTimer.Period - ...
    mTimer.UserData)/secondsPerMinute);
disp([str1 str2 str3])
end

Add a local function to handle the tasks associated with executing the timer. The TimerFcn callback should tell you to take a 30 second break.

function takeBreak(mTimer,~)
disp('Take a 30 second break.')
end

Add a local function to handle the tasks associated with stopping the timer.

function ergoTimerCleanup(mTimer,~)
disp('Stopping Ergonomic Break Timer.')
delete(mTimer)
end

Deleting the timer object removes it from memory.

From the command line, call the createErgoTimer function to create and start a timer.

t = createErgoTimer;
start(t)
Starting Ergonomic Break Timer.  For the next 8 hours you will be notified to take a 30 second break every 10 minutes.

Every 10 minutes, you will be reminded to take a 30 second break.

Take a break.

You can leave the timer running for 8 hours or stop it manually. Recall that you included the task of deleting the timer from memory in the StopFcn callback.

stop(t)
Stopping Ergonomic Break Timer.

Tips

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

Introduced before R2006a