I ran into the following issue in MATLAB R2013a, which for some reason I do not understand does not call the onCleanup function when in a function a timer (including a Timer
a possible workaround (found by a colleague of me) is to move to definition of the timer into a own function. It is not clear to us why this works but it seems that the definition of a timer in matlab changes the context of some local variables of the function which are not 'deleted' after the function ends as it would be expected from the matlab documentation (Object Life cycle of variables in Matlab)
A working example is shown below (it uses the defined timer to print simple status messages while waiting) and upon Ctrl+c or when the function ends the Timer is stopped. It furthermore makes sure that only one timer with the name 'timer-mywait' is defined.
function mytest3(time)
% register Cleanup handler
c = onCleanup(@()onCleanup_fcn);
t = mywait_timer(time);
wait(t);
% onCleanup handle function
function onCleanup_fcn
tm = timerfind('Name','timer-mywait');
if ~isempty(tm) && any(strcmpi(get(tm,'running'),'on'))
disp('Stopped running timer ''timer-mywait''!');
stop(tm);
end
end % onCleanup_fcn
end %mytest3
function t = mywait_timer(time)
N = 5;
t = timerfind('Name','timer-mywait');
if isempty(t) % avoid multiple definitions of the same timer
t = timer();
end
t.ExecutionMode = 'fixedRate';
t.TasksToExecute = N+1;
t.Period = str2num(sprintf('%.3f',time/N)); % Matlab complains about more digits!
t.Name = 'timer-mywait';
t.TimerFcn = @(o,s)mywait_timercb();
start(t),
end % mywait_timer
function mywait_timercb()
disp(' still waiting ... ');
end % mywait_timercb