【问题标题】:Pausing a loop for specific time at a specific time in R在R中的特定时间暂停特定时间的循环
【发布时间】:2017-09-25 20:27:44
【问题描述】:

我必须运行一个长循环来更新一些数据并将其存储在我公司的服务器中。问题是该公司在午夜运行备份例程,为此,他们关闭了服务器大约 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")
}

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

【问题讨论】:

    标签: r loops time


    【解决方案1】:

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

    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")
      }
    }
    

    【讨论】:

    • 喜欢重试方法。它允许我尝试在 15 分钟阈值之前返回循环,这可能只是例程完成所需时间的上限。
    • 太棒了!很高兴知道您喜欢它。
    猜你喜欢
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2014-03-23
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多