How can I put a stopwatch that counts how much time has passed since opening an app?
16 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
delete(app.startupTimer)
delete(app)
end
4 Comments
Adam Danz
on 8 Jan 2021
In case you're already not familiar with debugging methods in AppDesigner, here's a quick reminder:
You got this!
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!