Interrupt a timer wait functon immediately
조회 수: 2 (최근 30일)
이전 댓글 표시
I have a function that runs through an undetermined amount of iterations in 5 second intervals, until a user clicks the "cancel" button to stop it. For this button, I'm currently using the 'waitbar' function, and creating a cancel button ('canceling') on it.
Originally I was creating a new timer within each loop, and not using a "stop(t)" callback on the button, which resulted in waiting till the end of the loop before the cancel actions took place. I'm trying to have it stop the loop immediately when the cancel button is pressed. Changed to creating a timer that repeats as per Walter's suggestion, but it returns "t" as being undefined when trying to stop it, which I don't understand.
looping=0;
t=timer('TimerFcn',@(~,~)display('hello'),'StartDelay',5);
t.ExecutionMode='fixedRate';
t.TasksToExecute=1;
progress=waitbar(0,'1','Name','Logging Data...','CreateCancelBtn','stop(t);setappdata(gcbf,''canceling'',1);');
setappdata(progress,'canceling',0);
while looping==0
start(t)
display(datestr(now,'[HH,MM,SS]'))
wait(t);
looping=getappdata(progress,'canceling');
end
delete(progress)
Results when clicking cancel:
??? Error using ==> pause
Undefined function or variable 't'.
??? Error using ==> pause
Error while evaluating uicontrol Callback
Many thanks again for any suggestions.
댓글 수: 0
답변 (1개)
Walter Roberson
2015년 10월 11일
In MATLAB whenever you specify a string as a callback, the string is executed in the context of the base workspace, not in the context of the workspace that created the callback.
I do not understand why you are starting and stopping the timer on each loop.
Keep in mind that waitbar expects you to be calling waitbar() from time to time with updates of the progress fraction. If you just want a general cancel button then I would recommend implementing your own.
댓글 수: 2
Walter Roberson
2015년 10월 12일
See the StartDelay and the Period properties; http://www.mathworks.com/help/matlab/ref/timer-class.html
I do not know about R2014b and later, but in R2014a, the createcancelbtn property can be passed as a function handle instead of as a string.
progress = waitbar(0,'1','Name','Logging Data...','CreateCancelBtn', @(src,event) zapwait(src, event, t) );
function zapwait(src, event, t)
stop(t);
setappdata( ancestor(src, 'figure'), 'canceling' );
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Dialog Boxes에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!