Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

r - How do I run a function every second

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can keep track of the time with system.time

while(TRUE)
{
    s = system.time(Sys.sleep(runif(1, min = 0, max = 0.8)))
    Sys.sleep(1 - s[3]) #basically sleep for whatever is left of the second
}

You can also use proc.time directly (which system.time calls), which for some reasons got better results for me:

> system.time(
  for(i in 1:10)
  {
    p1 = proc.time()
    Sys.sleep(runif(1, min = 0, max = 0.8))
    p2 = proc.time() - p1
    Sys.sleep(1 - p2[3]) #basically sleep for whatever is left of the second
  })
   user  system elapsed 
   0.00    0.00   10.02

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...