Add a time limit for R expressions
timeout( expr, time_out = 1, on_timeout = { stop("Timout reached", call. = FALSE) }, on_final = { }, env = parent.frame() )
expr | expressions, wrap them inside |
---|---|
time_out | numeric, timeout time, in seconds |
on_timeout | expressions, callback expressions to run it the time out limit is reached but expression is still running. Default is to return an error. |
on_final | expressions, callback expressions to run in the end regardless the state and results |
env | environment, which environment to evaluate the expressions. Default is
the same environment as where the |
default return, all depends on what return the expr
will have
Expressions will be evaluated in the parent environment by default, for example
if this function is called at global level, all returns, assignments inside
expr
will directly go to global environment as well.
# The `try` command in following examples are here to make sure the # R CMD check will pass on package check. In a real case, you do not # need it. # default try(timeout({Sys.sleep(0.1)}, time_out = 0.01)) #> Error : Timout reached # timeout is evaluating expressions the same level as you call it timeout({abc <- 123}) # so you should get `abc` even outside the function call abc #> [1] 123 # custom timeout callback timeout({Sys.sleep(0.1)}, time_out = 0.01, on_timeout = {print("It takes too long")}) #> [1] "It takes too long" # final call back try(timeout({Sys.sleep(0.1)}, time_out = 0.01, on_final = {print("some final words")})) # on error #> [1] "some final words" #> Error : Timout reached timeout({123}, on_final = {print("runs even success")}) # on success #> [1] "runs even success" #> [1] 123 # assign to value my_val <- timeout({10 + 1}) my_val #> [1] 11