开发者

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 app开发者_StackOverflowears 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?


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."


For the hell of it, try:

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

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


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


Probably related to output buffering - see ?flush.console

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜