MATLAB: Running a Timer at a specific time

timed execution

T = timer('Period',120,... %period
'ExecutionMode','fixedRate',... %{singleShot,fixedRate,fixedSpacing,fixedDelay}
'BusyMode','drop',... %{drop, error, queue}
'TasksToExecute',inf,...
'StartDelay',0,...
'TimerFcn',@(src,evt)disp('hi'),...
'StartFcn',[],...
'StopFcn',[],...
'ErrorFcn',[]);
start(T);
Someone posted the above code in another post. My question is how can I modify the above so that it gets executed at a specific time, ie. 15:00:00.
thanks

Best Answer

AA - first we need to find the current time (in seconds) which we can do with the now function as
currentTimeSecs = rem(now,1)*24*60*60;
We multiply the remainder by 24 (hours) by 60 (minutes) and by 60 (seconds) to get the appropriate units (of seconds) for the current time. Now, we need to determine "where" this time is relative to 15:00:00 (the time at which we want to fire the timer). We can convert this to seconds as
fireTimerAtSecs = 15*60*60;
multiplying the number of hours (15) by 3600 to convert to seconds. The delay that you wish to add to the timer (so that it will fire at 15:00:00) is then
if currentTimeSecs < fireTimerAtSecs
% timer will fire today
timerDelaySecs = fireTimerAtSecs - currentTimeSecs;
else
% timer will fire tomorrow
timerDelaySecs = (24*60*60 - currentTimeSecs) + fireTimerAtSecs;
end
In the above, we need to account for whether the timer will fire later today or tomorrow depending upon the current time.
You can now use this delay as the StartDelay in your timer as
T = timer('Period',120, ...
'ExecutionMode','fixedRate', ...
'StartDelay', timerDelaySecs, ...
'TimerFcn',@(src,evt)disp('hi'));
start(T);
The above should invoke the timer after the expected delay, printing the message hi every 120 seconds thereafter.