How can I stop a script in MATLAB if a timer object needs more than a given number of seconds?

I run the matlab script several times a day, and many times it takes too much time to execute. I want to make a timer that keeps track of how long the script is running and stops the script when it takes more time than the specified number of seconds

I tested this principle with 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 is that this function waits 5 seconds and then executes the stop function, which is the error('Process ended because it took too long') command.

When this is done, the stop command will be executed, however it does not stop the execution of the main script.

In my command window I see

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

Then the script does not stop and continues to run for 10 seconds

I do not want this error to be executed on the TimerFcn function, I want this error to be executed on the running script in such a way that it stops working.

Is there any way to control the script / function that the error is running on?

+5
source share
3 answers

If you have access to the script and you can periodically check 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: CTRL + C implementation, but in code

Hope this will be helpful

+1
source

I agree with Ander Biguri that I do not think this is possible. What you can do is get TimerFcn to do something that causes an error, and something else.

 waittime = 5; d=1;go=1; t = timer('TimerFcn','clear d','StartDelay',waittime); start(t) while go pause(0.1) 1/d; end 
+1
source

Given this previous question , you probably have to resort to some Java tricks to do this, since throwing an error message does not interrupt pause . However, if a running script can periodically interrupt calculations and perform status checks, you can enable timer as follows:

 % Initialization: maxRunTime = 5; tObj = timer('TimerFcn', @(~, ~) disp('Time' up!'), 'StartDelay', maxRunTime); % Script: start(tObj); while strcmp(get(tObj, 'Running'), 'on') % Do some computations end delete(tObj); 

This checks the current state of the timer to determine if the cycle continues, so the timer function should not change any variables or throw any errors.

0
source

Source: https://habr.com/ru/post/1268100/


All Articles