Why does Timer callback experience "too many output arguments" errors?
Mostrar comentarios más antiguos
I am working on a Matlab Application which has a constantly running timer created in its StartupFcn:
% Build a new timer
app.refreshTimer = timer( ...
'Name', 'MATLAPP_RefreshTimer', ...
'Period', 0.1, ...
'ExecutionMode', 'fixedSpacing', ...
'TasksToExecute', Inf, ...
'TimerFcn', app.refreshTick());
% And start it
start(app.refreshTimer);
The function refreshTick() is actually empty and is a public method in the app.
methods (Access = public)
function refreshTick(app)
% Do nothing
disp(app.FUELPressButton.Value)
return
end
end
When the timer expires, I see the following error:
Error using gith/refreshTick
Too many output arguments.
Error in gith/startupFcn (line 93)
'TimerFcn', app.refreshTick());
Error in gith (line 594)
runStartupFcn(app, @startupFcn)
But the function has no output... why does this happen?
I can sidestep the issue by making the function anonymous:
% Build a new timer
app.refreshTimer = timer( ...
'Name', 'MATLAPP_RefreshTimer', ...
'Period', 0.1, ...
'ExecutionMode', 'fixedSpacing', ...
'TasksToExecute', Inf, ...
'TimerFcn', @(~,~)app.refreshTick());
% And start it
start(app.refreshTimer);
But I do not really understand why that works. I would love a solid technical explanation of what's happening here to cause this, if anyone understands this interaction.
Respuesta aceptada
Más respuestas (1)
Voss
el 3 de Abr. de 2022
Specifying the TimerFcn like this:
'TimerFcn', app.refreshTick(), ...
actually calls the function app.refreshTick, and then tries to set the TimerFcn to the result returned from calling app.refreshTick, but there is no result so you get the error. (Note that the error message says the error happens in startupFcn itself.)
Instead, specify it like this:
'TimerFcn', app.refreshTick, ...
because that refers to the function without calling it. The () on the end calls the function with no inputs.
2 comentarios
Walter Roberson
el 3 de Abr. de 2022
'TimerFcn', @app.refreshTick, ...
would refer to the function without calling it.
However the function would be called with two parameters. If the function is defined not to accept any parameters then @(~,~)app.refreshTick() or @(varargin) app.refreshTick() is appropriate
"Instead, specify it like this:'TimerFcn', app.refreshTick, because that refers to the function without calling it."
Are you sure about that (incorrect) statement?
" The () on the end calls the function with no inputs."
And what happens when there are no parentheses...?
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!