运行 预定义时间的 R 代码(纯粹在 R 中,没有任务管理器/cron 作业)

Running R code at predefined time (purely in R, no task manager / cron jobs)

我正在尝试编写一个允许 运行 在预先指定的时间使用 R 代码的循环。

这通常是使用 windows 中的任务 manager/taskscheduleR 完成的。但是对于这个特定的任务,我需要纯粹在 r 上执行它,因为我会将它转移到一个闪亮的小应用程序中。我把这个问题发到这里是为了它的闪亮部分 (Run shiny events at specified system times ),现在我需要确保我在 R 中有合适的代码,然后将在下一步处理闪亮的部分。

this 2012 post ( I want to run a R code at a specific time ), 提到了我在下面尝试过但没有用的方法。它应该打印“是时候了!”并在代码 运行.

后 10 秒打开 R 项目网页
time_to_run =  Sys.time()+10 #this defines the "target time", in this case, is 10 seconds later
while(TRUE) {
 
  if(Sys.time() == time_to_run) {
    print("It's time!")
    browseURL("https://www.r-project.org")
  }}

我也试过使用 repeat 循环,但还是没有得到足够的回应:

time_to_run =  Sys.time()+10
repeat {
  if(Sys.time() == time_to_run) {
    print("it's time!")
    browseURL("https://www.r-project.org")
 
  }
 
}

为什么这不起作用有什么建议吗?

提前致谢。

更新:

感谢下面来自 Jon Spring 的评论,我学会了如何在四舍五入后比较 Sys.time()

我现在不明白的是:如果我不在repeat循环中添加break,代码会无限次打开网页(如果你尝试,电脑可能会冻结,或者您必须重新启动 r)。不是应该在满足条件且两个时间点相等的情况下才运行代码(即打开网页)一次吗?有没有办法确保这种情况发生?

谢谢

library(lubridate)

time_to_run =  Sys.time()+5

 
repeat {
  if(round_date(Sys.time(),  unit = "second") == round_date(time_to_run,  unit = "second")) {
    print("it's time!")
    browseURL("https://www.r-project.org")
    break
  }
 
}

这是我使用的最终代码,它正在运行,post以防有人需要它。 可能有更好的方法来完成相同的任务(例如 shiny)但是对于这个我需要在 r

中使用
library(lubridate)

time_to_run =  Sys.time()+61

time_to_run = as.character(format(time_to_run, "%H:%M"))
 
repeat {
  noww = as.character(format(Sys.time(), "%H:%M"))
  
  print(noww)
  
  Sys.sleep(1)
  
  if(time_to_run == noww) {
    print("it's time!")
    browseURL("https://www.r-project.org")
    break
  }
 
}

不要做忙循环。使用 Sys.sleep:

Sys.sleep(10)
print("it's time!")
browseURL("https://www.r-project.org")

如果您想 运行 在设定的时间,而不是设定的延迟:

at_time <- Sys.time() + 3600  # 1 hour from now, or whenever

Sys.sleep(as.numeric(at_time - Sys.time())/1000)
print("it's time!")
browseURL("https://www.r-project.org")