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
creates an empty
t
= timertimer
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.
Specifies additional options that use one or more t
= timer(Name,Value
)Name-Value
arguments.
Properties
Callback Function Properties
TimerFcn
— Timer callback function
character vector | string scalar | function handle | cell array
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 theType
field and the time of the event in theData
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);")
StartFcn
— Timer start callback function
character vector | string scalar | function handle | cell array
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 theType
field and the time of the event in theData
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(~,~))
StopFcn
— Timer stop callback function
character vector | string scalar | function handle | cell array
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 ofTasksExecuted
reaches the limit set byTasksToExecute
.An error occurs. The
ErrorFcn
callback is called first, followed by theStopFcn
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 theType
field and the time of the event in theData
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(~,~))
ErrorFcn
— Timer error callback function
character vector | string scalar | function handle | cell array
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 theType
field and the time of the event in theData
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
Period
— Delay between executions
1 (default) | numeric scalar
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)
StartDelay
— Delay between start of timer and first execution
0 (default) | numeric scalar
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)
TasksToExecute
— Times timer callback function is executed
numeric scalar
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)
BusyMode
— Timer function callback queueing
'drop'
(default) | 'error'
| 'queue'
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.
| Behavior if Queue Empty | Behavior if Queue Not Empty | Notes |
---|---|---|---|
| Add task to queue | Drop task | Possible skipping of |
| Add task to queue | Complete task; throw error specified by
| Stops timer after completing task currently executing |
| Add task to queue | Wait for queue to clear, and then enter task in queue | Adjusts |
See Handling Timer Queuing Conflicts for more information.
Example: t = timer('BusyMode','error')
ExecutionMode
— Timer function callback scheduling
'singleShot'
(default) | 'fixedRate'
| 'fixedDelay'
| 'fixedSpacing'
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 |
---|---|
| The timer callback function is executed only once. Therefore, the
|
| Start immediately after the timer callback function is added to the MATLAB execution queue. |
| Start when the timer function callback restarts execution after a time lag due to delays in the MATLAB execution queue. |
| Start when the timer callback function finishes executing. |
'singleShot'
is the single execution mode for thetimer
class, and is the default value.'fixedDelay'
,'fixedRate'
, and'fixedSpacing'
are the three supported multiexecution modes. These modes define the starting point of thePeriod
property. ThePeriod
property specifies the amount of time between executions, which remains the same. Only the point at which execution begins is different.
Example: t = timer('ExecutionMode','fixedDelay')
Labeling properties
Name
— Timer name
'timer-i'
(default) | character vector | string scalar
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')
Tag
— Object label
character vector | string scalar
Object label, specified as character vector or string scalar.
Example: t = timer('Tag','TimerTag')
ObjectVisibility
— Object visibility
'on'
(default) | 'off'
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')
UserData
— Field for user data
any valid MATLAB data type
Generic field for data that you want to add to the object.
Example: t = timer('UserData',"This is my first
timer!")
Read-Only Properties
AveragePeriod
— Average time between executions
numeric scalar
Average time between executions, specified, in seconds, as a numeric scalar. Value
is NaN
until timer executes two timer callbacks.
InstantPeriod
— Time between the last two executions
NaN
(default) | numeric scalar
Time between the last two executions, specified, in seconds, as a numeric scalar.
Value is NaN
until timer executes two timer callbacks.
Running
— Indicator of actively executing callback functions
'off'
| 'on'
Indicator of actively executing callback functions, specified as
'off'
or 'on'
.
TasksExecuted
— Number of times timer has executed
numeric scalar
Number of times timer has executed, specified as a numeric scalar.
Type
— object type
'timer'
(default)
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
Display Message After Time Delay
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
Execute Callback Function Multiple Times
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
Define Custom Callback Functions
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 usingtimer
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. Thedrawnow
function flushes the event queue.
Version History
Introduced before R2006a
MATLAB 명령
다음 MATLAB 명령에 해당하는 링크를 클릭했습니다.
명령을 실행하려면 MATLAB 명령 창에 입력하십시오. 웹 브라우저는 MATLAB 명령을 지원하지 않습니다.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)