running a Timer at a specific time

조회 수: 2 (최근 30일)
AA
AA 2015년 1월 31일
답변: Geoff Hayes 2015년 2월 1일
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

채택된 답변

Geoff Hayes
Geoff Hayes 2015년 2월 1일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Code Execution에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by