简体   繁体   English

我想在特定时间运行 R 代码

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

I want to run a R code at a specific time that I need.我想在我需要的特定时间运行 R 代码。 And after the process finished, I want to terminate the R session.该过程完成后,我想终止 R 会话。

If a code is as below,如果代码如下,

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

What should I do to run this code at "2012-04-18 17:25:40".我应该怎么做才能在“2012-04-18 17:25:40”运行此代码。 I need your help.我需要你的帮助。 Thanks in advance.提前致谢。

It is easiest to use the Task Scheduler of Windows, or a cron job under Linux.使用Windows 的Task Scheduler 或Linux 下的cron 作业最容易。 There you can specify a command or program that should be run at a certain time you specify.您可以在那里指定应该在您指定的特定时间运行的命令或程序。

If somehow you cannot use the cron job service and have to schedule within R, the following R code shows how to wait a specific amount of time so as to execute at a pre-specified target time.如果不知何故您无法使用 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