Main Content

timer

Schedule execution of MATLAB commands

Description

Use a timer to schedule one or multiple executions of tasks comprised of MATLAB® callback functions. If a timer is scheduled to execute multiple times, you can specify the time between executions and how to handle queuing conflicts by adjusting the properties of the timer.

The timer object uses callback functions to execute commands. Callback functions execute code during some event, elapsed time in the case of timer. 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). For more information related to callback functions, see Timer Callback Functions.

Creation

Description

example

t = timer creates an empty timer object to schedule execution of MATLAB commands. Before starting the timer, you must set the TimerFcn property for the timer object.

A timer t has properties that control its behavior. Access a property by using p = t.Property and modify one using t.Property = p. To save and restore all properties of t, you can use A = get(t) and set(t,A), respectively.

example

t = timer(Name,Value) Specifies additional options that use one or more Name-Value arguments.

Properties

expand all

Callback Function Properties

Timer callback function, specified as a character vector, string scalar, function handle, or cell array. Before you can start a timer, you must define this property.

  • If you specify this property by 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 you specify this property by using a character vector or string scalar, when MATLAB executes the callback, it evaluates the MATLAB code contained in the character vector. Defining a callback as a character vector is not recommended. The use of a function specified as function handle enables MATLAB to provide important information to your callback function.

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

Example: t = timer('TimerFcn',"MyTimerFunction(Input);")

Timer start callback function, specified as a character vector, string scalar, function handle, or cell array.

  • If you specify this property by 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 you specify this property by using a character vector or string scalar, when MATLAB executes the callback, it evaluates the MATLAB code contained in the character vector. Defining a callback as a character vector is not recommended. The use of a function specified as function handle enables MATLAB to provide important information to your callback function.

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

Example: t = timer('StartFcn',@MyStartFunction(~,~))

Timer stop callback function, specified as a character vector, string scalar, function handle, or cell array.

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 cleanup actions, such as deleting the timer object from memory.

  • If you specify this property by 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 you specify this property by using a character vector or string scalar, when MATLAB executes the callback, it evaluates the MATLAB code contained in the character vector. Defining a callback as a character vector is not recommended. The use of a function specified as function handle enables MATLAB to provide important information to your callback function.

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

Example: t = timer('StopFcn',@MyStopFunction(~,~))

Timer error callback function, specified as a character vector, string scalar, function handle, or cell array. 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.

Example: t = timer('ErrorFcn','disp("An error has occurred")')

Timing Properties

Delay between executions, specified, in seconds, as a number greater than 0.001. For the timer to use Period, you must set ExecutionMode and TasksToExecute to schedule multiple timer object callback events.

Example: t = timer('Period',5)

Delay between start of timer and first execution, specified, in seconds, as a number greater than or equal to 0. When Running = 'on', StartDelay is read only.

Example: t = timer('StartDelay',2)

Times timer callback function is executed, specified as a number greater than 0. Use the TasksToExecute property to set the number of executions. To use TasksToExecute, you must set ExecutionMode to schedule multiple timer callback events. Changing TasksToExecute while the timer is running might not take effect immediately, depending on the state of the timer queue. For more information related to the timer queue, see Handling Timer Queuing Conflicts.

Example: t = timer('TasksToExecute',5)

Timer function callback queueing, specified as one of the values in the table. Use this property to specify the action taken when a timer has to execute TimerFcn before the completion of previous execution of the TimerFcn. When Running property is set to 'on', BusyMode property is read-only.

The BusyMode property affects behavior only when the ExecutionMode property is set to FixedRate. For other values of ExecutionMode, there cannot be overlapping attempts to execute the timer callback function because the delay between executions is always relative to the completion of the previous execution.

BusyMode Values

Behavior if Queue Empty

Behavior if Queue Not Empty

Notes

'drop'

Add task to queue

Drop task

Possible skipping of TimerFcn calls

'error'

Add task to queue

Complete task; throw error specified by ErrorFcn; stops timer

Stops timer after completing task currently executing

'queue'

Add task to queue

Wait for queue to clear, and then enter task in queue

Adjusts Period property to manage tasks in execution queue

See Handling Timer Queuing Conflicts for more information.

Example: t = timer('BusyMode','error')

Timer function callback scheduling, specified as one of the values in the table. When Running='on', ExecutionMode is read-only. This table summarizes the execution modes.

Execution Mode

Time Period Start Point

'singleShot'

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

'fixedRate'

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

'fixedDelay'

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

'fixedSpacing'

Start when the timer callback function finishes executing.

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

    Schematic of timing of 'singleShot' execution mode.

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

    Schematic of timing of 'fixedDelay' execution mode.

Example: t = timer('ExecutionMode','fixedDelay')

Labeling properties

Timer name, specified as a character vector or string scalar.

Defaults to 'timer-i', where i is a number indicating the ith timer object created this session.

Example: t = timer('Name','MyTimer')

Object label, specified as character vector or string scalar.

Example: t = timer('Tag','TimerTag')

Object visibility, specified as '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.

Example: t = timer('ObjectVisibility','off')

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

Example: t = timer('UserData',"This is my first timer!")

Read-Only Properties

Average time between executions, specified, in seconds, as a numeric scalar. Value is NaN until timer executes two timer callbacks.

Time between the last two executions, specified, in seconds, as a numeric scalar. Value is NaN until timer executes two timer callbacks.

Indicator of actively executing callback functions, specified as 'off' or 'on'.

Number of times timer has executed, specified as a numeric scalar.

Character vector that identifies the object type.

Object Functions

deleteDelete files or objects
getQuery graphics object properties
isvalidDetermine valid handles
setSet graphics object properties
startStart timer
startatSchedule timer to fire at specified time
stopStop timer
timerfindFind timer objects
timerfindallFind all timer objects
waitBlock command prompt until timer stops running

Examples

collapse all

Display a message after a time delay of 3 seconds by using a timer object.

Create a timer object. Specify the message to display by setting the TimerFcn property. Specify a time delay of 3 seconds by setting the StartDelay property to 3.

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

Start the timer.

start(t)

After three seconds, the message is displayed.

3 seconds have elapsed

Display the date and time when the timer starts and again 2 seconds later when the timer stops.

Display the date and time when the timer starts by setting the StartFcn property to a callback function. The first two arguments to the callback function are the timer object and an event structure with Type and Data fields. Similarly, display the date and time when the timer stops by setting the StopFcn property.

t = timer;
t.StartFcn = @(~,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;
start(t)
StartFcn executed 14-Jan-2020 09:08:50.865
StopFcn executed 14-Jan-2020 09:08:52.869

Display the date and time three times during execution with a two second pause between messages. Specify the message to display by setting the TimerFcn property. Then, indicate the number of times to display the message and the delay between each message by using the TasksToExecute and Period properties. ExecutionMode specifies that period timer starts when TimerFcn is called.

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

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

Create a function createErgoTimer that returns a timer object. Include three local functions to specify tasks when the timer starts, is executing, and stops.

Using StartDelay enables 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. You can stretch for 30 seconds before the start of the next 10 minute interval.

function t = createErgoTimer()

t = timer;
t.StartFcn = @ergoTimerStart;
t.TimerFcn = @takeBreak;
t.StopFcn = @ergoTimerCleanup;

% 10 minutes between breaks + 30 second break
t.Period = 600+30;

% time till first break
t.StartDelay = t.Period-30; 

% Number of breaks during 8-hr period
t.TasksToExecute = ceil(8*60^2/t.Period);
t.ExecutionMode = 'fixedSpacing';
end 

Add a local function callback associated with starting the timer. The task executed by StartFcn displays message indicating that the ergonomic timer has begun. By default, the timer object passes itself and event data to the callback function. The function disregards the event data.

function ergoTimerStart(mTimer,~)
disp("Starting Ergonomic Break Timer." + newline +...
"For the next 8 hours you will be notified " +...
"to take a 30 second break every 10 minutes.")
end

Add a local callback function that displays a message to take a 30 second break.

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

Add a local callback 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.

At 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 are reminded to take a 30 second break.

Take a break.

You can leave the timer running for 8 hours or stop it manually. The StopFcn callback includes the task of deleting the timer from memory.

stop(t)
Stopping Ergonomic Break Timer.

Limitations

  • The timer object is subject to the limitations of your hardware, operating system, and software. Avoid using timer objects for real-time applications. If MATLAB is busy processing another task, the timer callback might not execute.

  • Using wait inside timer callback functions is discouraged.

Tips

  • To force the execution of the callback functions in the event queue, include a call to the drawnow function. The drawnow function flushes the event queue.

Version History

Introduced before R2006a