Filter löschen
Filter löschen

Hi, I want 2 timer objects to execute sequentially, one after the other. Please help

3 Ansichten (letzte 30 Tage)
Suppose my program is as follows:
t = timer;
t.StartDelay = 3;
t.TimerFcn = @(myTimerObj, thisEvent)disp('hello');
t1 = timer;
t1.StartDelay = 5;
t1.TimerFcn = @(myTimerObj, thisEvent)disp('world');
I want my program to display 'hello' after 3 seconds, which it does. But it displays 'world' 2 seconds after 'hello' is displayed. i.e. simultaneous execution takes place.
I want 'world' to be displayed 5 seconds after 'hello' is displayed. And making the delay 8 is not the answer I'm looking for! I need sequential execution because I want to put it in an infinite loop.
It should display 'hello' after 3 seconds, and 5 seconds later 'world'. Then 3 more seconds later 'hello' should be displayed, and 5 seconds after that, 'world'. This is needed in an infinite loop.
Please help
Thank you!

Akzeptierte Antwort

Oleg Komarov
Oleg Komarov am 2 Mär. 2015
Bearbeitet: Oleg Komarov am 2 Mär. 2015
You can use one timer and a function that alternate the state(s):
t = timer;
t.ExecutionMode = 'fixedDelay';
t.StartDelay = 3;
t.TimerFcn = @(obj,evt) alternateState(obj);
% After you are done
clear persistent
And the state alternation is done by:
function alternateState(t)
persistent on
if isempty(on)
on = true;
if on
t.StartDelay = 5;
on = false;
t.StartDelay = 3;
on = true;
The state persists within the scope of the function.
Basically, you start the timer on repeated execution with fixed delay, and initial delay of 3. When the first time the function fires, it initializes the state to 'on', prints 'hello', sets the next delay to 5. On the next call, it reverts the delay back and prints 'world'.
Note, I am not sure this is clean, and would appreciate feedback, but it has the advantage to support several states. You can also clean away the tic/toc which is there for debugging purposes.
  3 Kommentare
Oleg Komarov
Oleg Komarov am 4 Mär. 2015
Actually, why do you think you need a timer? For the snapshot question, please ask it separately, since I have not used the function before and others might help.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)


Mehr zu GPU Computing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by