timer - Schedule execution of MATLAB commands - MATLAB (original) (raw)

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

Syntax

Description

`t` = timer creates an emptytimer object to schedule execution of MATLAB commands. Before starting the timer, you must set theTimerFcn 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 usingt.Property = p. To save and restore all properties oft, you can use A = get(t) andset(t,A), respectively.

example

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

example

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.

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.

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

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.

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 setExecutionMode 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 executeTimerFcn before the completion of previous execution of theTimerFcn. When Running property is set to'on', BusyMode property is read-only.

The BusyMode property affects behavior only when theExecutionMode 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 byErrorFcn; 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, thePeriod 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.

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_i_th 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

delete Delete files or objects
get Query graphics object properties
isvalid Determine valid handles
set Set graphics object properties
start Start timer
startat Schedule timer to fire at specified time
stop Stop timer
timerfind Find timer objects
timerfindall Find all timer objects
wait Block 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.

After three seconds, the message is displayed.

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 theStartFcn 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 theTimerFcn property. Then, indicate the number of times to display the message and the delay between each message by using theTasksToExecute and Period properties.ExecutionMode specifies that period timer starts whenTimerFcn 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 atimer 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 aTimerFcn 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 a30 second 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.

Stopping Ergonomic Break Timer.

Limitations

Tips

Version History

Introduced before R2006a