Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Set execution time limit in loop

Tags:

r

I have a script that uses the rNOMADS package to download forecast data. Currently, it uses a for loop to call the forecast download function for each three hour forecast interval in order. The issue is the download function occasionally "freezes" at random which forces me to terminate R and start the process over. When it freezes the code hangs at the download function for minutes instead of the typical <1 sec it takes to execute, and then when I try to halt execution I get a message saying "R is not resrponding to your request to interrupt processing so to stop the current operation you may need to terminate R entirely."

Is there a way set a time limit for a specific block of code to execute in each for loop iteration, and then skip that block of code and throw an error if the time limit is reached? Something like tryCatch, that I could use to raise a flag to re-do that for loop iteration?

Something like:

for (i in 1:N) {
   ...

   setTimeLimit(XXX seconds) {
      downloadFunction()
   } timeLimitReached {
      doOverFlag <- 1
   }
}

Thanks in advance!

like image 863
Peter Avatar asked Jul 16 '15 19:07

Peter


Video Answer


2 Answers

The function evalWithTimeout of package R.utils does this.

evalWithTimeout(Sys.sleep(10), timeout = 1)

(times are in seconds).

Note: I have not used this function a lot, I liked your question so I did some googling around and found this.

like image 26
kasterma Avatar answered Nov 14 '22 10:11

kasterma


This function works as follows now:

library(R.utils)
withTimeout(Sys.sleep(10), timeout = 1)#stop execution after one second
like image 60
Alexander Avatar answered Nov 14 '22 10:11

Alexander