DrewConway
DrewConway

Reputation: 5457

Functions not executing before Sys.sleep()

I am writing a function that needs to catch a rate-limiting error while pinging a web-based API.

I am using tryCatch to catch the error, and inside this function I specify the following error function:

error=function(e) {
                warning(paste(e,"\nWaiting an hour for rate limit to reset..."))
                Sys.sleep(3600) # Wait an hour for rate-limit to reset
                return(user.info(user, ego.count))
            }

The function appears to work, but when checking the output logs for the script I notice that the warning message is not written until after the sleep time has run out.

I can reproduce this behavior at the R console with:

print("Drew sucks")
Sys.sleep(10)

Ten seconds pass before Drew sucks is printed to the console. In my function, I would like to provide some feedback to the user about this long pause before the pause happens.

What is causing this behavior?

Upvotes: 7

Views: 3958

Answers (4)

Joshua Ulrich
Joshua Ulrich

Reputation: 176718

You need to either set immediate.=TRUE to your warning function, or set options(warn=1); and may need to add flush.console() (on some operating systems) before the Sys.sleep() call.

foo <- function() {
  warning("uh-oh...", immediate.=TRUE)
  flush.console()
  Sys.sleep(5)
  "done"
}
foo()
# Warning in foo() : uh-oh...
# [1] "done"

The specifics are spelled out in the "Details" section of ?warning. To paraphrase, "if options(warn=0), warnings are stored and printed after the top-level function has completed; if options(warn=1) they are printed as they occur."

Upvotes: 8

mjbommar
mjbommar

Reputation: 499

For the hell of it, try:

system(sprintf('sleep %d', seconds))

Assuming you've got the usual *NIX sleep command on path.

Upvotes: 3

geoffjentry
geoffjentry

Reputation: 4754

By default, warnings aren't printed immediately, instead they are printed out after the top level function returns. You can set warn to '1' if you want it to print out immediately, and even higher if you want it to stop

Upvotes: 3

hadley
hadley

Reputation: 103948

Probably related to output buffering - see ?flush.console

Upvotes: 2

Related Questions