How do I run a function every second

Viewed 9967

I want to run a function that takes less than one second to execute. I want to run it in a loop every second. I do not want to wait one second between running the function like Sys.sleep would do.

while(TRUE){
  # my function that takes less than a second to run
  Sys.sleep(runif(1, min=0, max=.8))  

  # wait for the remaining time until the next execution...
  # something here
}

I could record a starttime <- Sys.time() and do a comparison every iteration through the loop, something like this...

starttime <- Sys.time()
while(TRUE){
  if(abs(as.numeric(Sys.time() - starttime) %% 1) < .001){
    # my function that takes less than a second to run
    Sys.sleep(runif(1, min=0, max=.8))  
    print(paste("it ran", Sys.time()))
  }
}

But my function never seems to be executed.

I know python has a package to do this sort of thing. Does R also have one that I don't know about? Thanks.

5 Answers

Another non-blocking alternative worth mentioning is provided by library(later), via using later() recursive:

print_time = function(interval = 10) {
  timestamp()
  later::later(print_time, interval)
}

print_time()

The example is taken from here.

Although its very late.

As an alternative we can use recursion. I don't know if its the solution you are looking for. But it executes function at regular interval.

ssc <-  function(){
x <- rnorm(30,20,2)
print(hist(x))
 Sys.sleep(4)

 ssc()

 }
ssc()
Related