Pregunta

I need to execute a function at given delays. Let's say I have a vector [0.5,1,0.6], I want the function to be executed after 0.5 second, then after 1 second and finally after 0.6 seconds.

Up to now I've tried a combination of pause(), but the result is way far from accurate and I would like to use pause inside the function, so the handling of my initial offsets (in time) may be cumbersome.

Are there any other possibilities that allow to do this? If there's an error margin of up to 10ms I don't really care.

Thanks

¿Fue útil?

Solución

Maybe create an array of timer objects in singleShot mode, with start times computed from the cumulative sum of the delays:

delays = [0.5, 1, 0.6];
startTimes = cumsum(delays);

timerFcn = @(~,thisEvent) disp([thisEvent.Type ' executed '...
     datestr(thisEvent.Data.time,'dd-mmm-yyyy HH:MM:SS.FFF')]);

for ii=1:numel(delays),
    T(ii) = timer('StartDelay',startTimes(ii),'TimerFcn',timerFcn,...
        'ExecutionMode','singleShot');
end

Then you can launch all the timers simultaneously:

>> start(T); fprintf('Launching timers: %s\n',datestr(now,'dd-mmm-yyyy HH:MM:SS.FFF'))
Launching timers: 21-Mar-2014 12:14:46.780
TimerFcn executed 21-Mar-2014 12:14:47.280
TimerFcn executed 21-Mar-2014 12:14:48.280
TimerFcn executed 21-Mar-2014 12:14:48.880

That seems fairly accurate.

Now instead of calling disp to print the date and time, launch your function.

EDIT: Do NOT forget to delete the timers (delete(T)) and/or stop them, especially if the timers are created in a GUI, otherwise they will keep running. Thanks for the reminder, @Daniel.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top