timer

Creates a timer object that runs a function after a delay or repeatedly.

Category: Programming > Programming Utilities

Syntax

t = timer

Creates a timer with default settings.

t = timer(Name, Value, ...)

Creates a timer and sets properties such as 'TimerFcn', 'StartDelay', 'Period', 'ExecutionMode', 'TasksToExecute' or 'Name'.

Description

Creating a timer does nothing by itself; start arms it and stop disarms it. The timer calls TimerFcn in the background of the session, which makes it useful for polling, animations and delayed actions. Properties can be read and set with dot notation, for example t.Period = 0.5, and TasksExecuted counts how many times it fired.

A timer that is no longer needed should be removed with delete(t).

Input arguments

TimerFcn
Function handle called each time the timer fires. It receives the timer object and an event structure.
StartDelay
Seconds to wait after start before the first call. Default 0.
Period
Seconds between calls for repeating modes. Default 1.
ExecutionMode
'singleShot' (default), 'fixedRate', 'fixedDelay' or 'fixedSpacing'.
TasksToExecute
Number of times to fire in repeating modes. Default Inf.

Output arguments

t
Timer object. It is a handle: copies refer to the same timer.

Example

Three beats at a fixed rate

t = timer('ExecutionMode', 'fixedRate', 'Period', 0.01, ...
          'TasksToExecute', 3, 'TimerFcn', @(~,~) disp('beat'));
start(t)
wait(t)
disp(t.TasksExecuted)
delete(t)
Output
beat
beat
beat
     3

See also

start stop wait timerfind delete