有什么方法可以根据文件的存在而不是具体时间来触发cron任务的运行?

问题描述 投票:0回答:2

我想在R中使用cron r或任务调度器来运行一个基于每天更新的.CSV文件的脚本。有一点是,CSV文件的更新并没有特定的时间(比如说在420的时候,它在下午3点更新,但在421的时候,它在下午2:30更新,在422的时候,它在下午12点更新)。主要的触发因素不是一天的时间,而是文件每天的存在。有什么方法可以让我使用R插件来运行这个程序吗?我在工作中使用服务器,所以我没有使用windows任务调度程序,因为R不在我的机器上。

r automation cron taskscheduler
2个回答
0
投票

与其每天运行cron任务,不如每5分钟运行一次(或一些合理的时间间隔),并跟踪它处理文件的时间。比如说

needswork <- function(filename, expr, updated = paste0(filename, ".seen")) {
  if (!file.exists(filename)) return(FALSE)
  if (!file.exists(updated)) return(TRUE)
  return(file.info(updated)$mtime < file.info(filename)$mtime)
}
donework <- function(filename, expr, updated = paste0(filename, ".seen")) {
  writeLines(character(0), updated)
}

if (needswork("/path/to/mainfile.csv")) {
  # process the file here
  # ...
  # update
  donework("/path/to/mainfile.csv")
}

我可能会延长 needswork 一点点增加通知问题,如

needswork <- function(filename, expr, updated = paste0(filename, ".seen")) {
  if (!file.exists(filename)) return(FALSE)
  if (difftime(Sys.time(), file.info(filename)$mtime, units="secs") > 60*60*24) {
    some_notify_function()
    # perhaps something like
    msg <- paste("The file", sQuote(filename), "has not been updated since",
                 file.info(filename$mtime))
    RPushbullet::pbPost("note", title = "No recent updates", body = msg)
  }
  if (!file.exists(updated)) return(TRUE)
  return(file.info(updated)$mtime < file.info(filename)$mtime)
}

0
投票

Cron是严格的基于时间的调度器。

说到这里,有一个变通的方法。

  1. 创建一个脚本(例如:mycron.py),如下所示
import os.path

if os.path.isfile("/tmp/myfile.csv"):
  # File exists
  # Do something
else:
  # File does not exist
  pass
  1. 将这个脚本(mycron.py)运行时间安排在 定期

Python脚本只是一个例子。欢迎使用你喜欢的脚本语言

© www.soinside.com 2019 - 2024. All rights reserved.