如果使用R连接失败,请重新连接
我已经编写了一个小函数,但不知怎么的,它并没有像预期的那样工作 我已连接到服务器,有时服务器已关闭,因此无法连接。脚本正在批量运行,因此我必须将其自动化如果使用R连接失败,请重新连接,r,R,我已经编写了一个小函数,但不知怎么的,它并没有像预期的那样工作 我已连接到服务器,有时服务器已关闭,因此无法连接。脚本正在批量运行,因此我必须将其自动化 脚本应运行conn,如果您只想在连接建立过程中循环,这将起作用: # simulate an instable connection server.connect <- function(...) { if (round(as.numeric(Sys.time())) %% 10 != 0) # about 90 % failed c
脚本应运行
conn,如果您只想在连接建立过程中循环,这将起作用:
# 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)
我很难完全理解您的代码,但您的函数定义的最后一行包括connect(c-1)
,您是否试图使用带有自己定义的函数connect?@bmrn:您是对的,实际上是connect(c-1)是冗余的,并且绝对不应该在调用函数中…您的目的只是尝试连接,直到成功建立连接,还是希望在进一步处理步骤(需要以幂等方式重新启动处理)中再次丢失连接时重新连接?谢谢你调查这件事。没有检查和重新连接,如果连接丢失是不需要的,但这是事实上,我希望这个功能能做到。我已经通过模拟连接测试了编辑功能,首先在没有internet连接的情况下运行该功能(现在该功能每1:10 o 6秒检查一次,在该功能运行后,我连接到internet,现在我希望该功能在下一次迭代中pics up并连接到服务器(如果可用…)所发生的情况是,该函数没有拾取稍后连接的可能性。。。
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)
# 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..."