Это демонстрация того, как настроить прерывание callback
. При настройке вашего примера я не видел необходимости в реальном таймере, поэтому я сделал это в качестве стандартного обратного вызова кнопки.
примечание: Если вы не можете использовать его для таймера, вы можете использовать точно такое же решение, просто назначьте обратный вызов startProcess
для таймера вместо кнопки gui.
function h = interuptible_callback_demo
% generate basic gui with 2 buttons
h = create_gui ;
guidata( h.fig , h )
% create application data which will be used to interrupt the process
setappdata( h.fig , 'keepRunning' , true )
end
function startProcess(hobj,~)
h = guidata( hobj ) ;
% set the 'keepRunning' flag
setappdata( h.fig , 'keepRunning' , true )
% toggle the button states
h.btnStart.Enable = 'off' ;
h.btnStop.Enable = 'on' ;
nGrainOfSand = 1e6 ;
for k=1:nGrainOfSand
% first check if we have to keep running
keepRunning = getappdata( h.fig , 'keepRunning' ) ;
if keepRunning
% This is where you do your lenghty stuff
% we'll count grains of sand for this demo ...
h.lbl.String = sprintf('Counting grains of sands: %d/%d',k,nGrainOfSand) ;
pause(0.1) ;
else
% tidy up then bail out (=stop the callback)
h.lbl.String = sprintf('Counting interrupted at: %d/%d',k,nGrainOfSand) ;
% toggle the button states
h.btnStart.Enable = 'on' ;
h.btnStop.Enable = 'off' ;
return
end
end
end
function stopProcess(hobj,~)
h = guidata( hobj ) ;
% modify the 'keepRunning' flag
setappdata( h.fig , 'keepRunning' , false )
end
function h = create_gui
h.fig = figure('units','pixel','Position',[200 200 350 200]) ;
h.btnStart = uicontrol('style','pushbutton','string','Start process',...
'units','pixel','Position',[50 100 100 50],...
'Callback',@startProcess) ;
h.btnStop = uicontrol('style','pushbutton','string','Stop process',...
'units','pixel','Position',[200 100 100 50],...
'Callback',@stopProcess,'enable','off') ;
h.lbl = uicontrol('style','text','string','','units','pixel','Position',[50 20 200 50]) ;
end
Чтобы увидеть это в действии:
![enter image description here](https://i.stack.imgur.com/YSiLc.gif)