Can timers trigger a single event that many objects listen to?

6 views (last 30 days)
I have several objects that I want to run a function every second. Is it possible to set up a timer to trigger an event, have all of the objects listen for that event, and run the function and update themselves? Is there a better way to accomplish the goal of having updates every second?

Accepted Answer

Patrick Kalita
Patrick Kalita on 8 Aug 2011
Sure, that's entirely possible. You can wrap the basic MATLAB timer in an object that broadcasts an event (via the notify method). Then you can use the addlistener method within the "client" class to respond to those notifications.
Here's a basic example. This is the class that defines and broadcasts the events on a regular interval via a timer:
classdef TimerObj < handle
properties
theTimer
end
events
TimerEvent
end
methods
function this = TimerObj
this.theTimer = timer( ...
'ExecutionMode', 'fixedRate', ...
'Period', 1, ...
'TimerFcn', @(src, evt) this.notify( 'TimerEvent' ) );
start(this.theTimer);
end
function delete(this)
stop(this.theTimer);
end
end
end
Here's a class that can listen to those events:
classdef UserObj < handle
properties
Name
end
methods
function this = UserObj( aName )
this.Name = aName;
end
function listenToTimer(this, timerobj)
addlistener( timerobj, 'TimerEvent', @(src, evt) this.onTimerEvent );
end
function onTimerEvent(this)
disp( [this.Name ' responding to TimerEvent!'] );
end
end
end
Now they can be used together like this:
>> a = UserObj('Alice');
>> b = UserObj('Bob');
>> t = TimerObj;
>> a.listenToTimer(t);
Alice responding to TimerEvent!
Alice responding to TimerEvent!
>> b.listenToTimer(t)
Bob responding to TimerEvent!
Alice responding to TimerEvent!
Bob responding to TimerEvent!
Alice responding to TimerEvent!
Bob responding to TimerEvent!
Alice responding to TimerEvent!
Bob responding to TimerEvent!
Alice responding to TimerEvent!
>> delete(t)
>>
A lot of this is just a repackaging of this documentation example. So you might want to read through that, too.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by