Using a timer to iterate through a for loop

조회 수: 9 (최근 30일)
Scott Brainard
Scott Brainard 2019년 6월 19일
댓글: dpb 2019년 6월 20일
I am trying to use a timer to advance to the next iteration of a for loop, if a function called within the for loop takes more than 5 seconds to complete:
for n = 1 : tot
t = timer('TimerFcn', 'continue', 'StartDelay', 5);
start(t)
[pmsk{n}, crv{n}, mline{n}, smsk{n}, tcrd{n}, dsts{n}] = runStraighteningPipeline(img.readimage(n)); %% This is the process I am trying to end if it keeps running for more than 5 seconds
fname{n} = getDirName(img.Files{n});
msg = sprintf('Successfully processed: %s', fname{n}); disp(msg);
stop(t)
delete(t)
end
However, I receive the following error when the timer elapses:
Error while evaluating TimerFcn for timer 'timer-10'
Error: A CONTINUE may only be used within a FOR or WHILE loop.
I assume this is because MATLAB is running code within "runStraighteningPipeline", and isn't explicitly within the for loop when the timer is triggered. Is there any way around this?
I don't want to break out of the loop, I just want to advance to the next value of "n", if this subprocess takes too long.
Thanks!
  댓글 수: 3
Scott Brainard
Scott Brainard 2019년 6월 20일
That's a good idea. When I tried it out though, I get the same problem as this user:
So:
for n = 1 : tot
try
t = timer('TimerFcn', 'error("timeout")', 'StartDelay', 3);
start(t)
[pmsk{n}, crv{n}, mline{n}, smsk{n}, tcrd{n}, dsts{n}] = runStraighteningPipeline(img.readimage(n));
fname{n} = getDirName(img.Files{n});
msg = sprintf('Successfully processed: %s', fname{n}); disp(msg);
catch e
% fprintf(2, 'Error in Carrot Pipeline\n%s\n', e.getReport);
continue
end
stop(t)
delete(t)
end
Returns
Error while evaluating TimerFcn for timer 'timer-1'
timeout
Without actually catching the error and advancing
dpb
dpb 2019년 6월 20일
I think you'll have to get more subtle than that...the timer will need a function body, and, I'm guessing, to rethrow the error as caller. Will need to probe the MException stack to determine just how that is organized and, if there are other functions inside the runStraighteningPipeline function as almost certainly will be, you may have to walk your way back up the stack from several levels of nesting dependent upon where execution is at the time the timer fires.
This may not be fun and may, (or may not) even be doable, I don't know for certain...this might be one to pose over on the Matlab Undocumented site for Yair--it's the kind of thing he's probably poked around at at some time or the other...

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by