r-lib / later

Schedule an R function or formula to run after a specified period of time.
https://r-lib.github.io/later
Other
137 stars 27 forks source link

Stop later function #146

Closed cedlfc44 closed 3 years ago

cedlfc44 commented 3 years ago

Hi: How can i stop later loop, because i need to save some variables that i produce inside loop every hour for example. My example code is below. Thanks for your help saveZ<-c() library(later) print_time = function(interval = 10) { Z<-timestamp() saveZ<-rbind(saveZ, Z) later::later(print_time, interval) } print_time()

wch commented 3 years ago

I'm not sure exactly what you're doing, but I think you might want something like this:

saveZ <- c()
library(later)

cancel <- NULL
print_time <- function(interval = 1) {
  Z <- timestamp()
  saveZ <<- c(saveZ, Z)
  cancel <<- later::later(print_time, interval)
}

print_time()

# To stop, call cancel()
cancel()

later() returns a function which will cancel the scheduled callback. I used <<- to assign it to a scope outside of the print_time function. Calling cancel() at any time will stop this from running.

Similarly, the saveZ needed to be assigned with <<-.