Peter Peter - 1 year ago 128
R Question

R - Set execution time limit in loop

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) {
} timeLimitReached {
doOverFlag <- 1

Thanks in advance!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download