Skip to content

Instantly share code, notes, and snippets.

@thisisnic
Created October 30, 2024 14:20
Show Gist options
  • Save thisisnic/6b76bf3678feb91fdfba84ea66f1f3a3 to your computer and use it in GitHub Desktop.
Save thisisnic/6b76bf3678feb91fdfba84ea66f1f3a3 to your computer and use it in GitHub Desktop.
function for interrupting an R function execution if takes too long
foo <- function() {
time_limit <- 3
setTimeLimit(cpu = time_limit, elapsed = time_limit, transient = TRUE)
on.exit({
setTimeLimit(cpu = Inf, elapsed = Inf, transient = FALSE)
})
tryCatch({
Sys.sleep(3.5)
print("done")
}, error = function(e) {
if (grepl("reached elapsed time limit|reached CPU time limit", e$message)) {
print("interrupted")
# we reached timeout, apply some alternative method or do something else
} else {
# error not related to timeout
stop(e)
}
})
}
foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment