Alert sound/mail for warning me if the program runs overtime.
3 次查看(过去 30 天)
显示 更早的评论
Is there any way to notify me if a function I call doesn't return a result in 20seconds. (I am not allowed to make any change to the function. I can change only the main function which calls the function.)
Is it possible to run two codes parallel; one the function and the other a timer.
Thank you.
0 个评论
回答(2 个)
Walter Roberson
2017-1-31
Yes, barely. You can use parfeval() to start the routine. After 20 seconds, check the status of the "future" that it returns; if it has not finished then cancel the future, and otherwise collect its result.
Note: any routine you run this way will not have access to graphics.
0 个评论
dbmn
2017-1-31
Another option is to use the timer function. But it is kind of tricky and not as nice.
clear all; close all; clc
% Initialize variables
finished_1 = false;
finished_2 = false;
% Run first Function
disp('FUNCTION 1')
start(timer('TimerFcn',{@checkfun, 'finished_1'},'StartDelay',1.5));
finished_1 = myfun1();
pause(1)
% Run second Function
start(timer('TimerFcn',{@checkfun, 'finished_2'},'StartDelay',1.5));
disp('FUNCTION 2')
finished_2 = myfun2();
%%Function declarations
function [finished] = myfun1()
pause(1);
finished = true;
end
function [finished] = myfun2()
pause(2);
finished = true;
end
function [] = checkfun(~, ~, varname)
finished = evalin('base',varname); % if you pass a variable it will take one without delay
if finished
disp('finished')
else
disp('not finished')
end
end
3 个评论
dbmn
2017-2-6
You are right. Thank you for clarifying the points of interuptions of the timer function - i didn't know that.
There is one way to cancel the execution if it goes on for too long - but it rather nasty by introducing try/catch statements with exceptions.
finished_1 = false;
try
start(timer('TimerFcn',{@checkfun, 'finished_1'},'StartDelay',1.5));
finished_1 = myfun1();
catch
% continue
end
while trowing an exception in the checkfun of the timer, if the execution takes too long.
function [] = checkfun(~, ~, varname)
finished = evalin('base',varname);
if ~ finished
error('my special error')
end
end
not nice, but lets you stop the current execution and resume with the rest of the code
Walter Roberson
2017-2-6
The timer lives in a different execution context, just like graphics interrupts do. You cannot catch errors generated in callbacks by any routine outside the callback.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Entering Commands 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!