How to stop a "timer" inside a handle "class" when the handle is cleared in MATLAB?

I'm trying to find the best way to stop a timer inside a handle class when the handle is cleared. I am passing the object to the timer which allows me to query the class properties. On running the script "test_class.m", when I perform the "clear" command, the timer keeps on running. The only way that I can prevent this is to call the "delete" command. Is there a way of writing this class with a timer such that a simple "clear" command is able to stop the timer?

 Accepted Answer

"clear" does not delete handle objects. It deletes their references. When the reference count to a handle object drops to 0 (i.e., when the last reference was cleared), then MATLAB deletes the object (that is the deletion does not come from clear, but from MATLAB's tracking of reference counts). In this case, a situation has been created where it is not possible to clear the last reference as it is in the timer object (especially as it gets out of scope after variable test is cleared), so the reference count to the handle object remains 1 (or more).
A workaround to this is to introduce a wrapper object as mentioned in the scripts below:
%%%%% exampleHandle.m %%%%%
classdef exampleHandle
methods
function timerFired(~,~,~)
display("Timer Fired")
end
function delete(~)
disp("Handle Deleted")
end
end
end
%%%%%% objectwrapper.m %%%%%
classdef objectwrapper > handle
properties
TimerObject
HandleObject
end
methods
function obj = objectwrapper(varargin)
obj.HandleObject = exampleHandle(varargin{:});
obj.TimerObject = setTimerFcn(obj.HandleObject);
start(obj.TimerObject)
end
function delete(obj)
stop(obj.TimerObject);
delete(obj.TimerObject);
disp("Timer Deleted")
delete(obj.HandleObject);
end
end
end
function t = setTimerFcn(h)
t = timer(Period = 1, ...
ExecutionMode = "fixedRate", ...
TimerFcn = @(~,~)h.timerFired());
end
now on executing:
w = objectwrapper
the "TimerFired" event shows up. Now, on executing:
clear w
the timer will stop as required.

More Answers (0)

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!