Search code examples
rtimer

Set a timer in R to execute a program


I have a program to execute per 15 seconds, how can I achieve this, the program is as followed:

print_test<-function{
    cat("hello world")
}

Solution

  • What I use for executing same code block every 15 seconds:

    interval = 15
    x = data.frame()
    
    repeat {
      startTime = Sys.time()
      x = rbind.data.frame(x, sum(data)) #replace this line with your code/functions
      sleepTime = startTime + interval - Sys.time()
      if (sleepTime > 0)
        Sys.sleep(sleepTime)
    }
    

    x and data are dummy which you need to replace accordingly. This will execute indefinitely until stopped by user. If you need to stop and start at specific times then you need a for loop instead of 'repeat`.

    Hope this helps.