转载:http://cn.mathworks.com/help/matlab/ref/timer-class.html
timer class
Create object to schedule execution of MATLAB commands
Description
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).
Note:The timer object is subject to the limitations of your hardware, operating system, and software. Avoid using timer objects for real-time applications.
Construction
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. Input Arguments
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. Default: ‘on’ Default: 1.0 Default: 0
Properties
AveragePeriod | Average time in seconds between TimerFcn executions since the timer started. Value is NaN until timer executes two timer callbacks. |
InstantPeriod | The time in seconds between the last two executions of TimerFcn. Value is NaN until timer executes two timer callbacks. |
Running | String defined as ‘off’ or ‘on’, indicating whether the timer is currently executing callback functions. |
TasksExecuted | The number of times the timer called TimerFcn since the timer started. |
Type | String 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, see Copying Objects in the MATLAB documentation.
Examples
Display Message Using Timer
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.
delete(t) |
Execute Callback Function Multiple Times
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.
delete(t) |
Define Custom Callback Functions
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.
n 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.
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.
stop(t) |
Stopping Ergonomic Break Timer.
Tips
- 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.
See Also
function_handle
More About
- Timer Callback Functions
- Handling Timer Queuing Conflicts
- Ignore Function Outputs
- Property Attributes
Leave a Reply