MATLAB Answers

How can I put a stopwatch that counts how much time has passed since opening an app?

21 views (last 30 days)
Lorenzo Corso
Lorenzo Corso on 7 Jan 2021
Commented: Adam Danz on 8 Jan 2021
Hi everyone, I searched the net but unfortunately I didn't understand how to do it. What I would like to do is quite simple:
I want to measure the time that passes since I open an app and, if it exceeds a certain threshold (e.g. 3 minutes), then I have to assign the value 1 to a variable.
Thanks in advance,
Lorenzo

Accepted Answer

Adam Danz
Adam Danz on 7 Jan 2021
Edited: Adam Danz on 7 Jan 2021
> I want to measure the time that passes since I open an app
Create a timer object in the startup function of the App and start the timer at the end of the startup function. Set the timer callback function to update the variable after 3 minutes. The variable should be stored within the app, either as an app component or as a public property.
Timers can be tricky to set up if you haven't done so before so I recommend reading the links I provided to get a sense of how the timer will work. If you get stuck, specifically indicate what step you're stuck on, what you tried, and I'd be happy to help set things straight.
Add timer to App that starts when app opens and changes variable after a fixed delay
See attached timerDemo.mlapp which contains these 4 steps.
1. Declare the timer and the variable to be updated as a private property (or public, if needed). Alternatively, the variable to be updated might be an app component such as a text field which would not need to be declared as an app propery.
properties (Access = private)
startupTimer % timer obj created in startupFcn
timeExpired = 0; % updated by app.startupTimer
end
2. Create timer in startupFcn(); start the timer at the end of the startupFcn.
function startupFcn(app)
app.startupTimer = timer('Name','startupTimer','ExecutionMode','singleShot', ...
'ObjectVisibility','off','StartDelay',3*60, ... %StartDelay is in seconds
'TimerFcn',@(~,~)updateValue(app,1));
start(app.startupTimer) % <--- at the end of the startupFcn
end
To run the same timer again, just execute start(app.startupTimer).
3. Define the variable-update function that is evoked by the timer after the StartDelay (how to add helper function)
function updateValue(app,TF)
% Evoked by app.startupTimer; sets app.timeExpired to the value in TF.
app.timeExpired = TF;
end
4. Delete the timer when the app closes. Add a close request function to the app.
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
delete(app.startupTimer)
delete(app)
end
  4 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!