簡體   English   中英

我想在特定時間運行 R 代碼

[英]I want to run a R code at a specific time

我想在我需要的特定時間運行 R 代碼。 該過程完成后,我想終止 R 會話。

如果代碼如下,

tm<-Sys.time()
write.table(tm,file='OUT.TXT', sep='\t');
quit(save = "no")

我應該怎么做才能在“2012-04-18 17:25:40”運行此代碼。 我需要你的幫助。 提前致謝。

使用Windows 的Task Scheduler 或Linux 下的cron 作業最容易。 您可以在那里指定應該在您指定的特定時間運行的命令或程序。

如果不知何故您無法使用 cron 作業服務並且必須在 R 中進行調度,以下 R 代碼顯示了如何等待特定時間以便在預先指定的目標時間執行。

stop.date.time.1 <- as.POSIXct("2012-12-20 13:45:00 EST") # time of last afternoon execution. 
stop.date.time.2 <- as.POSIXct("2012-12-20 7:45:00 EST") # time of last morning execution.
NOW <- Sys.time()                                        # the current time
lapse.time <- 24 * 60 * 60              # A day's worth of time in Seconds
all.exec.times.1 <- seq(stop.date.time.1, NOW, -lapse.time) # all of afternoon execution times. 
all.exec.times.2 <- seq(stop.date.time.2, NOW, -lapse.time) # all of morning execution times. 
all.exec.times <- sort(c(all.exec.times.1, all.exec.times.2)) # combine all times and sort from recent to future
cat("To execute your code at the following times:\n"); print(all.exec.times)

for (i in seq(length(all.exec.times))) {   # for each target time in the sequence
  ## How long do I have to wait for the next execution from Now.
  wait.time <- difftime(Sys.time(), all.exec.times[i], units="secs") # calc difference in seconds.
  cat("Waiting for", wait.time, "seconds before next execution\n")
  if (wait.time > 0) {
    Sys.sleep(wait.time)   # Wait from Now until the target time arrives (for "wait.time" seconds)
    {
      ## Put your execution code or function call here
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM