Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop a script in MATLAB when it takes longer than a specified number of seconds using the timer object? [duplicate]

Tags:

matlab

I run a matlab script multiple times per day and a lot of times it takes too long to execute. What I want to do is set off a timer that keeps track of how long the script has been running for and stops the script when it takes longer than a specified number of seconds

I have tested this principle on a simple script:

waittime = 5;
t = timer('TimerFcn','error(''Process ended because it took too long'')',waittime); 
start(t)
pause(10);

What I would expect to happen is that this function waits for 5 seconds and afterwards it will execute the stop function which is the error('Process ended because it took too long') command.

When running this, the stop command will execute, however it does not stop the main script from running.

In my command window I see

Error while evaluating TimerFcn for timer 'timer-20' 
Process ended because it took too long

Afterwards the script is not stopped, and keeps running for the full 10 seconds

I don't want this error to be cast over the TimerFcn function, I want this error to be cast over the running script such that it stops running.

Is there any way I can control the script/function over which the error is cast?

like image 723
Nordin Avatar asked Oct 29 '22 07:10

Nordin


2 Answers

If you have access to the the script and can periodically check for the time inside the script, you can do something like this

waittime = 3;
endt=true;
t = timer('TimerFcn','endt=false; disp(''Timer!'')','StartDelay',waittime); 
start(t);

i=1;
while endt==true
    a=exp(i);
    i=i+1;
    pause(0.1);
end

If you do not have any bits that are periodic or do not have access to the script, I think your best bet is described here

Matlab: implementing what CTRL+C does, but in the code

Hope this is helpful

like image 146
Vahe Tshitoyan Avatar answered Nov 15 '22 10:11

Vahe Tshitoyan


I agree with Ander Biguri that I don't think this is possible. What you can do is make the TimerFcn do something that causes an error somehwere else.

waittime = 5;
d=1;go=1;
t = timer('TimerFcn','clear d','StartDelay',waittime); 
start(t)
while go
    pause(0.1)
    1/d;
end
like image 42
Gelliant Avatar answered Nov 15 '22 09:11

Gelliant