Documentation

timer class

Create object to schedule execution ofMATLABcommands

Description

Use atimerobject 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.

Thetimerobject uses callback functions to execute commands. Callback functions execute code during some event. For thetimerobject, 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

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

Construction

t=计时器creates an emptytimerobject to schedule execution of MATLAB commands. An error occurs if the timer starts andTimerFcnis not defined.

t=计时器(Name,Value)creates atimerobject with additional options that you specify using one or moreName,Valuepair arguments.

Input Arguments

Name-Value Pair Arguments

Specify optional comma-separated pairs ofName,Valuearguments.Nameis the argument name andValueis the corresponding value.Namemust appear inside single quotes (' '). You can specify several name and value pair arguments in any order asName1,Value1,...,NameN,ValueN.

The argument name,Name, corresponds to atimerproperty name. In the constructor, the property values are specified usingName,Valuepair arguments.

'BusyMode'

Character vector that indicates action taken when a timer has to executeTimerFcnbefore the completion of previous execution of theTimerFcn. WhenRunning='on',BusyModeis read only. This table summarizes the busy modes.

BusyModeValues

Behavior if Queue Empty

Behavior if Queue Not Empty

Notes

'drop'

Adds task to queue

Drops task

Possible skipping ofTimerFcncalls

'error'

Adds task to queue

Completes task; throws error specified byErrorFcn; 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

AdjustsPeriodproperty to manage tasks in execution queue

SeeHandling Timer Queuing Conflictsfor more information.

Default:'drop'

'ErrorFcn'

Character vector, 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 callsStopFcn.

  • If you specify this property using a character vector, 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 thetimerobject and an event structure to the callback function. The event structure contains the type of event in theTypefield and the time of the event in theDatafield.

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

For more information, seeTimer Callback Functions.

'ExecutionMode'

特征向量定义w thetimerobject schedules timer events. WhenRunning='on',ExecutionModeis read only. This table summarizes the execution modes.

Execution Mode

TimePeriodStart Point

'singleShot'

In this mode, the timer callback function is only executed once. Therefore, thePeriodproperty 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 thetimerclass, and is the default value.

  • 'fixedDelay','fixedRate', and'fixedSpacing'是三个支持mul吗金宝apptiexecution modes. These modes define the starting point of thePeriodproperty. ThePeriodproperty 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 representing thetimername.

Default:'timer-i', whereiis a number indicating theith timer object created this session. To resetito 1, execute theclear classescommand.

'ObjectVisibility'

Character vector 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. Thetimerfindfunction does not return an object whoseObjectVisibilityproperty 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 thetimerfindallfunction.

Default:'on'

'Period'

Number greater than 0.001 that specifies the delay, in seconds, between executions ofTimerFcn. For the timer to usePeriod,你必须设置ExecutionModeandTasksToExecuteto 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 inTimerFcn. WhenRunning = 'on',StartDelayis read only.

Default:0

'StartFcn'

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

  • If you specify this property using a character vector, 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 thetimerobject and an event structure to the callback function. The event structure contains the type of event in theTypefield and the time of the event in theDatafield.

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

For more information, seeTimer Callback Functions.

'StopFcn'

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

  • If you specify this property using a character vector, 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 thetimerobject and an event structure to the callback function. The event structure contains the type of event in theTypefield and the time of the event in theDatafield.

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

For more information, seeTimer Callback Functions.

The timer stops when

  • You call the timerstopmethod.

  • The timer finishes executingTimerFcn. In other words, the value ofTasksExecutedreaches the limit set byTasksToExecute.

  • An error occurs. TheErrorFcncallback is called first, followed by theStopFcncallback.

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

'Tag'

Character vector that represents a label for the object.

'TasksToExecute'

Number greater than 0, indicating the number of times the timer object is to execute theTimerFcncallback. Use theTasksToExecuteproperty to set the number of executions. To useTasksToExecute,你必须设置ExecutionModeto schedule multiple timer callback events.

Default:Inf

'TimerFcn'

Character vector, 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, 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 thetimerobject and an event structure to the callback function. The event structure contains the type of event in theTypefield and the time of the event in theDatafield.

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

For more information, seeTimer Callback Functions.

'UserData'

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

Properties

AveragePeriod

Average time in seconds betweenTimerFcnexecutions since the timer started. Value isNaNuntil timer executes two timer callbacks.

InstantPeriod

The time in seconds between the last two executions ofTimerFcn. Value isNaNuntil 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 calledTimerFcnsince the timer started.

Type

Character vector that identifies the object type.

Methods

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

Copy Semantics

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

Examples

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

Wait3seconds, 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:Typeis a character vector that identifies the type of event that caused the callback, andDatais 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 namedcreateErgoTimer.mthat returns a timer object. Have this file include three local functions to handle timer start, execute, and stop tasks.

functiont = 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

UsingStartDelayallows the timer to start without directing you to take a break immediately. Set the execution mode to'fixedSpacing'so that10minutes and30seconds (t.Period) elapses after the completion of aTimerFcnexecution. This allows you to stretch for30seconds before the start of the next10minute interval.

In thecreateErgoTimer.mfile, add a local function to handle the tasks associated with starting the timer. By default, thetimerobject passes itself and event data to the callback function. The function disregards the event data.

functionergoTimerStart(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. TheTimerFcncallback should tell you to take a30second break.

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

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

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

Deleting the timer object removes it from memory.

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

t = createErgoTimer; start(t)
从人体工程学的计时器。在接下来的8侯rs you will be notified to take a 30 second break every 10 minutes.

Every10minutes, you will be reminded to take a30second break.

Take a break.

You can leave the timer running for8hours or stop it manually. Recall that you included the task of deleting the timer from memory in theStopFcncallback.

stop(t)
Stopping Ergonomic Break Timer.

Tips

  • To force the execution of the callback functions in the event queue, include a call to thedrawnowfunction in your code. Thedrawnowfunction flushes the event queue.

Introduced before R2006a

Was this topic helpful?