Main Content

timerfind

Find timer objects

Description

out = timerfind finds the visible timer objects and returns an array, out.

example

out = timerfind(Name,Value) finds visible timer objects that have property values matching those passed as Name,Value arguments and returns an array out. Value can be an empty array. In this case, timerfind finds timers that have empty values for the property specified by Name.

example

out = timerfind(t,Name,Value) matches Name,Value pair arguments to the timer objects listed in t, where t can be an array of timer objects, and returns an array, out.

out = timerfind(S) matches property values defined in the structure S and returns an array out. The field names of S are timer object property names. The field values are the corresponding property values.

Examples

collapse all

Create several individual timers and an array of timers.

t1 = timer('Tag','broadcastProgress','UserData','Monday');
t2 = timer('Tag','displayProgress','UserData','Monday');
timerArr = [timer('Tag','broadcastProgress','UserData','Tuesday');
    timer('Tag','displayProgress','UserData','Tuesday');
    timer('Tag','displayProgress','UserData','Wednesday');];

Find all the timers in memory.

out1 = timerfind
out1 = 
Timer Object Array

   Index:  ExecutionMode:  Period:  TimerFcn:               Name:
   1       fixedSpacing    30       @(~,~)logStack()        timer-1
   2       singleShot      1        ''                      timer-2
   3       singleShot      1        ''                      timer-3
   4       singleShot      1        ''                      timer-4
   5       singleShot      1        ''                      timer-5
   6       singleShot      1        ''                      timer-6

Find only those timers in memory that have the Tag property value 'displayProgress'.

out2 = timerfind('Tag','displayProgress')
out2 = 
Timer Object Array

   Index:  ExecutionMode:  Period:  TimerFcn:               Name:
   1       singleShot      1        ''                      timer-3
   2       singleShot      1        ''                      timer-5
   3       singleShot      1        ''                      timer-6

Limit the search for timers to timer objects in timerArr with the Tag property value 'displayProgress'.

out3 = timerfind(timerArr,'Tag','displayProgress')
out3 = 
Timer Object Array

   Index:  ExecutionMode:  Period:  TimerFcn:               Name:
   1       singleShot      1        ''                      timer-5
   2       singleShot      1        ''                      timer-6

Define a struct containing the Tag and UserData properties of interest.

searchStruct = struct('Tag','broadcastProgress','UserData','Monday')
searchStruct = struct with fields:
         Tag: 'broadcastProgress'
    UserData: 'Monday'

Use the struct as the search criteria to find timer objects in memory.

out4 = timerfind(searchStruct)
out4 = 
   Timer Object: timer-2

   Timer Settings
      ExecutionMode: singleShot
             Period: 1
           BusyMode: drop
            Running: off

   Callbacks
           TimerFcn: ''
           ErrorFcn: ''
           StartFcn: ''
            StopFcn: ''

Delete the timer objects.

delete(t1)
delete(t2)
delete(timerArr)

Use the timerfind function to stop multiple timers at the same time even when the timer variables have been removed from the workspace.

Create two timer objects that generate 100 random numbers and executes 1,000,000 times. Define a StopFcn callback that displays the message 'Timer has stopped.' Start the timers and verify that the timer is running

t1 = timer('TimerFcn','rand(100,1);',...
    'ExecutionMode','fixedSpacing','TasksToExecute',1e6,...
    'StopFcn','disp(''Timer1 has stopped.'')');
t2 = timer('TimerFcn','rand(100,1);',...
    'ExecutionMode','fixedSpacing','TasksToExecute',1e6,...
    'StopFcn','disp(''Timer2 has stopped.'')');
start([t1 t2])

Clear the timer variables from the workspace.

clear

Use timerfind to manually stop the timers and verify that they are no longer running.

stop(timerfind)
t1.Running
ans = 
'off'
t2.Running
ans = 
'off'

Delete the timers.

delete(timerfind)

Simulate having existing timers in memory by creating an array of timers. Create a timer with a custom name. List all visible timers.

existingTimers = [timer timer timer];

myTimerName = 'myTimer';
anotherTimer = timer('Name',myTimerName);

timerfind
Timer Object Array

   Index:  ExecutionMode:  Period:  TimerFcn:               Name:
   1       singleShot      1        ''                      timer-1
   2       singleShot      1        ''                      timer-2
   3       singleShot      1        ''                      timer-3
   4       singleShot      1        ''                      myTimer

Delete the specified timer and list all visible timers.

delete(timerfind('Name',myTimerName));
timerfind
Timer Object Array

   Index:  ExecutionMode:  Period:  TimerFcn:               Name:
   1       singleShot      1        ''                      timer-1
   2       singleShot      1        ''                      timer-2
   3       singleShot      1        ''                      timer-3

Delete all visible timers from memory.

delete(timerfind)

Use timerfind to find ‘lost' timer object references. References are lost when you clear the timer object from the workspace, but do not delete it from memory.

Create two timer objects. Because the callback function does not require the timer or event object, you can use the tilde (~) operator to ignore the inputs in the function handle.

t1 = timer('TimerFcn',@(~,~)disp('Timer 1 Fired!'));
t2 = timer('TimerFcn',@(~,~)disp('Timer 2 Fired!'));
whos
  Name      Size            Bytes  Class    Attributes

  t1        1x1               104  timer              
  t2        1x1               104  timer   

Clear one of the timer objects from the workspace. To remove the timer from memory, clear it and delete it.

clear t1
whos
  Name      Size            Bytes  Class    Attributes

  t2        1x1               104  timer              

Try to delete the timer, t1.

delete(t1)
Undefined function or variable 't1'.

The timer t1 cannot be removed from memory by using delete because its reference has been cleared.

Find valid timer objects in memory.

out = timerfind
Timer Object Array

   Index:  ExecutionMode:  Period:  TimerFcn:               Name:
   1       singleShot      1        1x1 function_handle arraytimer-1
   2       singleShot      1        1x1 function_handle arraytimer-2

Since two timers were found, determine which timer does not exist in the workspace.

out ~= t2
ans =

     1     0

The first timer object in out is not equal to t2. This object was previously t1. It is reassigned to t1. Because it is still valid, you can start the timer.

t1 = out(1);
start(t1)
Timer 1 Fired!

Delete timer objects. Use timerfind to access timer objects in memory. It does not copy the objects, so you do not need to delete out from memory. To verify that the timers have been deleted, use timerfind.

delete(t1)
delete(t2)
timerfind
ans =

     []

Create four timer objects.

t1 = timer('TimerFcn',@(~,~)disp('Timer 1 Fired!'));
t2 = timer('TimerFcn',@(~,~)disp('Timer 2 Fired!'));
t3 = timer('TimerFcn',@(~,~)disp('Timer 3 Fired!'));
t4 = timer('TimerFcn',@(~,~)disp('Timer 4 Fired!'));

Clear two timers from the workspace.

clear t2 t3

Pass timerfind to delete to remove all timer objects from memory, whether or not they exist in the workspace.

delete(timerfind)
timerfind
ans =

     []

Input Arguments

collapse all

Timer to be found, specified as a timer object or array of timer objects

Example: out = timerfind(t)

Structure that has field names corresponding to timer property names. Field values are the corresponding property values.

Example: out = timerfind(S)

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: out = timerfind('BusyMode','drop')

Callback Function Properties

collapse all

Timer callback function, specified as a character vector, string scalar, function handle, or cell array. You must define this property before you can start the 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.

  • 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 the Type field and the time of the event in the Data 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);")

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 the Type field and the time of the event in the Data 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(~,~))

Timer stop 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 the Type field and the time of the event in the Data 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.

The timer stops when:

  • You call the timer stop method.

  • The timer finishes executing TimerFcn. In other words, the value of TasksExecuted reaches the limit set by TasksToExecute.

  • An error occurs. The ErrorFcn callback is called first, followed by the StopFcn callback.

You can use StopFcn to define cleanup actions, such as deleting the timer object from memory.

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.

  • 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 the Type field and the time of the event in the Data 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

collapse all

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)

Delay between start of timer and first execution, specified, in seconds, as a number greater than or equal to zero. When Running = 'on', StartDelay is read only.

Example: t = timer('StartDelay',2)

Times timer callback function is executed, specified as a number greater than zero. Use the TasksToExecute property to set the number of executions. To use TasksToExecute, you must set ExecutionMode to schedule multiple timer callback events.

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

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 by ErrorFcn; stops timer

Stops timer after completing task in execution queue

'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 only executed once. Therefore, the Period 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.

  • 'singleShot' is the single execution mode for the timer class, and is the default value.

    Schematic of timing of 'singleShot' execution mode.

  • 'fixedDelay', 'fixedRate', and 'fixedSpacing' are the three supported multiexecution modes. These modes define the starting point of the Period property. The Period property specifies the amount of time between executions, which remains the same. Only the point at which execution begins is different.

    Schematic of timing of 'fixedDelay' execution mode.

Example: t = timer('ExecutionMode','fixedDelay')

Labeling properties

collapse all

Timer name, specified as a character vector or string scalar.

Defaults to '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.

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', so that you can 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

collapse all

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.

Output Arguments

collapse all

Found timer objects, returned as an array of timer objects.

More About

collapse all

visible timer objects

Visible timer objects are timer objects that are in memory and have the ObjectVisibility property set to 'on'.

Tips

  • timerfind finds only visible timer objects. Visible timer objects are those objects that are in memory and have the ObjectVisibility property set to 'on'. To find objects that are hidden, but still valid, use timerfindall.

Version History

Introduced before R2006a

See Also

| | | |