timeout {spsUtil}R Documentation

Run expressions with a timeout limit

Description

Add a time limit for R expressions

Usage

timeout(
  expr,
  time_out = 1,
  on_timeout = {     stop("Timout reached", call. = FALSE) },
  on_final = { },
  env = parent.frame()
)

Arguments

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 timeout function is called.

Details

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.

Value

default return, all depends on what return the expr will have

Examples

# 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))
# 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
# custom timeout callback
timeout({Sys.sleep(0.1)}, time_out = 0.01, on_timeout = {print("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
timeout({123}, on_final = {print("runs even success")})  # on success
# assign to value
my_val <- timeout({10 + 1})
my_val

[Package spsUtil version 0.2.2 Index]