r - 在R中的特定时间暂停特定时间的循环

标签 r loops time

我必须运行一个长循环来更新一些数据并将其存储在我公司的服务器中。问题是该公司在午夜运行备份程序,为此,他们将服务器关闭了大约 15 分钟。

因此,鉴于我必须为每次迭代写下一个文件,当服务器出现故障时,它会中断循环。

我设法通过如下编写循环来规避问题

for(i in bills.list){
  url = paste0("ulalah",i,"/")
  # Download the data
  bill.result <- try(getURL(url)) # if there is an error try again
  while(class(bill.result)=="try-error"){
    Sys.sleep(1)
    bill.result <- try(getURL(url))
  }

# if iteration is between 23:59:00 and 23:59:40 wait 17 min to restart the loop
  if(as.numeric(format(Sys.time(), "%H%M%S")) > 235900 &
     as.numeric(format(Sys.time(), "%H%M%S")) < 235940){

    Sys.sleep(1020)

  }
  # Write the page to local hard drive
  write(bill.result, paste0("bill", i, ".txt"))

  # Print progress of download
  cat(i, "\n")
}

问题是,通过评估所有迭代的时间,我失去了一些宝贵的时间。有更有效的想法吗?

最佳答案

我认为您可以简单地尝试存储日期。如果失败,可能是你在备份窗口内

store <- function(data, retry = 10) {
  while(retry > 0) {
    result <- try(write(data, "/some_broken_place"))
    if(class(result) == "try-error") {
      # it might be we are in the backup window 
      cat("I will sleep if it turns out that it's backup time")
      if(as.numeric(format(Sys.time(), "%H%M%S")) > 235900 &
         as.numeric(format(Sys.time(), "%H%M%S")) < 235940){
        Sys.sleep(1020)
      }
      retry <- retry - 1
    }
  }
  if(retry == 0) {
    cat("Very, very bad situation - no chance to store data")
  }
}

关于r - 在R中的特定时间暂停特定时间的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43668011/

相关文章:

r - 在 r 中的 data.table 中缩放

r - ggplot2中的scale_colour_gradient2不能准确显示低或高的颜色?

python - 在扩展的圆形螺旋中迭代二维数组

python - 如何退出循环

c# - 不同时刻的节目时间

python - 如何将 float 转换为时分秒?

r - R 的 Plotly 中的两个 X 轴

r - 按 2 组汇总数据

bash - 在 bash 循环参数列表中注释

java - 时差忽略时区差异