Create object to schedule execution of MATLAB commands
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 string. If the callback function is a string, 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).
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.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside single 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.
String 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.
See Handling Timer Queuing Conflicts for more information.
String, 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.
String that defines how the timer object schedules timer events. When Running='on', ExecutionMode is read only. This table summarizes the execution modes.
String 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.
String 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.
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.
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.
String, function handle, or cell array defining the function that executes when the timer starts.
String, function handle, or cell array defining the function that executes when the timer stops. The timer stops when
You can use StopFcn to define clean up actions, such as deleting the timer object from memory.
String that represents a label for the object.
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.
String, function handle, or cell array defining the timer callback function. You must define this property before you can start the timer.
Generic field for data that you want to add to the object.
Average time in seconds between TimerFcn executions since the timer started. Value is NaN until timer executes two timer callbacks.
The time in seconds between the last two executions of TimerFcn. Value is NaN until timer executes two timer callbacks.
String defined as 'off' or 'on', indicating whether the timer is currently executing callback functions.
The number of times the timer called TimerFcn since the timer started.
String that identifies the object type.
|delete||Remove timer object from memory|
|get||Query property values for timer object|
|isvalid||Determine timer object validity|
|set||Set property values for timer object|
|start||Start timer object|
|startat||Schedule timer to fire at specified time|
|stop||Stop timer object|
|timerfind||Find timer object|
|timerfindall||Find timer object, regardless of visibility|
|wait||Block command prompt until timer stops running|
Handle. To learn how handle classes affect copy operations, see Copying Objects in the MATLAB documentation.
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.
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 string 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.
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.
Stopping Ergonomic Break Timer.
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.