4

I have one r function i want to run it automatically(scheduling) after every predefined time interval (example after every 5 mins) Is it possible if yes then how it can be done.

amonk
  • 1,769
  • 2
  • 18
  • 27
jan5
  • 1,129
  • 3
  • 17
  • 28
  • 1
    `Sys.sleep()` at the end of the function is what you want, as @DavidHefferman shows. Here is an example of a simple function that runs every 60 s: http://stackoverflow.com/a/9950670/1036500 – Ben Apr 09 '12 at 08:17
  • 2
    @Ben That function doesn't run every 60s. It restarts 60s after it finishes. If it takes 2 seconds to run then it runs every 62s. Anyway, that's a pretty minor point, but I'm just pedantic like that! ;-) – David Heffernan Apr 09 '12 at 08:36

1 Answers1

14

Ideally you should use the system scheduler for this: cron on a Unix system or Scheduled Tasks on a Windows system.

There may be some requirement that means you can't spawn a new process for each invocation of the function. If so then use an infinite loop with a call to Sys.sleep() to wait until the next invocation is due.

repeat {
    startTime <- Sys.time()
    runFunction()
    sleepTime <- startTime + 5*60 - Sys.time()
    if (sleepTime > 0)
        Sys.sleep(sleepTime)
}
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    Even this potentially could be off by microseconds -- the time required to exit `Sys.sleep` , return to top, and calculate `startTime` :-) . The truly A-C amongst us could calculate `initTime<-Sys.time()` prior to the loop and increment by by 300 every time thru the loop (then compare `initTime` to `Sys.time`). – Carl Witthoft Apr 09 '12 at 11:21
  • @carl maybe so but I bet that, even though R is sluggish, the resolution of Sys.time() is coarser then the time taken to return from Sys.sleep and go back to the start of the loop. ;-) – David Heffernan Apr 09 '12 at 11:27