6

I want to run a R code at a specific time that I need. And after the process finished, I want to terminate the R session.

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". I need your help. Thanks in advance.

j08691
  • 204,283
  • 31
  • 260
  • 272
TaeHeon Kim
  • 125
  • 1
  • 8
  • 1
    Have you considered going outside R and using `cron`? Some leads: [Using cron](http://www.scrounge.org/linux/cron.html), on [Linux](http://kevin.vanzonneveld.net/techblog/article/schedule_tasks_on_linux_using_crontab/), [Windows cron equivalent](http://stackoverflow.com/questions/132971/what-is-the-windows-version-of-cron) or [OSX](http://superuser.com/questions/243893/how-to-make-run-cron-on-osx-10-6-2) – daedalus Apr 18 '12 at 07:29
  • I solved this problem using task scheduler and batch file. Thanks :) – TaeHeon Kim Apr 19 '12 at 05:10

2 Answers2

15

It is easiest to use the Task Scheduler of Windows, or a cron job under Linux. There you can specify a command or program that should be run at a certain time you specify.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
5

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.

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
    }
  }
}
Feiming Chen
  • 119
  • 2
  • 3