如果使用R连接失败,请重新连接

时间:2018-05-22 20:54:21

标签: r

我写了一些小函数,但不知何故不按预期工作。

我已连接到服务器,有时服务器已关闭,因此无法连接。该脚本是批量运行的,所以我必须让它自动化。

如果不是conn <- function(..),脚本应该成功运行restart/re-check(这意味着没有错误消息),并在约。 1分钟的时间。这应该在循环中运行,直到建立连接大约12小时。 (大约)。应将连接分配给conn对象,以便对象必须返回成功连接。 (类似于<Connection established, @ 20180522 20:43:41 CET>

不起作用的功能在这里:

connect <- function(c) { message(paste("remaining run", c)); 
                     withRestarts(err <- tryCatch({ conn <- server.coonect(settings...) }, 
                     error=function(e) { invokeRestart("reconnect") }), reconnect = function() { message("re-connecting"); 
                     stopifnot(c > 0); for(i in 1:10) { Sys.sleep(6); cat(i) }; connect(c-1) }) }

connect(1000) # with approx. 1min sleep we get here over 12 hours running..

所以问题是什么是错的以及如何重写函数,使其按预期运行。感谢。

修改

似乎该功能应该是:

connect <- function(c) { message(paste("remaining run", c)); 
                 withRestarts(err <- tryCatch({ server.coonect(settings...) }, 
                 error=function(e) { invokeRestart("reconnect") }), reconnect = function() { message("re-connecting"); 
                 stopifnot(c > 0); for(i in 1:10) { Sys.sleep(6); cat(i) } }) }

conn <- connect(1000) 

编辑2

以下是我测试的上述功能的评论:

我已经通过首先运行没有互联网连接的功能来模拟连接来测试EDIT功能(现在该功能每隔1:10 osec检查一次,并且在功能运行后我连接到互联网,现在我期待功能在下一次迭代中pics up并连接到服务器(如果可用的话......)会发生的是该函数没有获得后来连接的可能性......

1 个答案:

答案 0 :(得分:1)

如果您只想循环连接建立,这将起作用:

# simulate an instable connection
server.connect <- function(...) {
  if (round(as.numeric(Sys.time())) %% 10 != 0) # about 90 % failed connections
    stop("Connection error")
  return(TRUE)  # success
}

connect <- function(attempts = 1, sleep.seconds = 6) {
  for (i in 1:attempts) {
    res <- try(server.connect("my connection string"), silent = TRUE)
    if (!("try-error" %in% class(res))) {
      print("Connected...")
      return(res)
    }
    print(paste0("Attempt #", i, " failed"))
    Sys.sleep(sleep.seconds)
  }
  stop("Maximum number of connection attempts exceeded")
}

con <- connect(attempts = 10, sleep = 1)

执行日志示例:

[1] "Attempt #1 failed"
[1] "Attempt #2 failed"
[1] "Attempt #3 failed"
[1] "Attempt #4 failed"
[1] "Attempt #5 failed"
[1] "Attempt #6 failed"
[1] "Connected..."
相关问题