每25小时运行一次的Cronjob?

12

我该如何设置一个每 25 小时运行一次的 cron 作业?


1
这是什么目的?为什么24小时不可接受? - Mike Cooper
参见:https://dev59.com/2HRB5IYBdhLWcg3wAjXR - mob
2
从谷歌过来,有一个合法的用例,就是避免超过每日 API 限制,针对一个不特别时间敏感的定期作业。增加一个额外的小时以保守为原则,并避免夏令时错误。 - mahemoff
6个回答

17

仅仅猜测,但是你

我能想到的最好的技巧是:编写一个脚本来跟踪上一次运行的时间,并在超过25小时后有条件地运行它。

将该驱动脚本安排在cron中每小时运行。


7

当您启动当前任务时,可以更容易地发出指定下一个作业的时间和日期的 at 命令,但是您可以通过更新进程的 cronjob 条目来模拟它,在当前运行开始时进行(不是在结束时,因为那样您需要考虑运行作业所需的时间)。


如果您错过了一个作业,例如系统在计划运行时宕机,那么“at”技巧可能会失败。 - Keith Thompson

2

设置一个每小时运行的任务,并在您的脚本中检查是否已经过去了25个小时,使用以下代码片段:

if [ $((((`date +%s` - (`date +%s` % 3600))/3600) % 25)) -eq 0 ] ; then
 your script 
fi

2
更多的评论将不胜感激。此代码生成时间戳(自纪元以来的秒数),将其转换为小时,并检查模25(因此每25小时)。如果需要,在特定日期更改“-eq 0”为“-eq 10”以更改小时... - darkless

2

如果你计算自 Epoch 以来的小时数(分钟数、天数或周数),并在脚本顶部添加一个条件,将脚本设置为在你的 crontab 中每小时运行,那么你就可以实现任何频率。

#!/bin/bash

hoursSinceEpoch=$(($(date +'%s / 60 / 60')))

# every 25 hours
if [[ $(($hoursSinceEpoch % 25)) -ne 0 ]]; then
    exit 0
fi

date(1) 命令返回当前日期,我们将其格式化为自纪元以来的秒数(%s),然后进行基本数学运算:

# .---------------------- bash command substitution
# |.--------------------- bash arithmetic expansion
# || .------------------- bash command substitution
# || |  .---------------- date command
# || |  |   .------------ FORMAT argument
# || |  |   |      .----- formula to calculate minutes/hours/days/etc is included into the format string passed to date command
# || |  |   |      |
# ** *  *   *      * 
  $(($(date +'%s / 60')))
# * *  ---------------
# | |        | 
# | |        ·----------- date should result in something like "1438390397 / 60"
# | ·-------------------- it gets evaluated as an expression. (the maths)
# ·---------------------- and we can store it

你可以将这种方法用于分钟、小时、天或月的定时任务:

#!/bin/bash
# We can get the

minutes=$(($(date +'%s / 60')))
hours=$(($(date +'%s / 60 / 60')))
days=$(($(date +'%s / 60 / 60 / 24')))
weeks=$(($(date +'%s / 60 / 60 / 24 / 7')))

# or even

moons=$(($(date +'%s / 60 / 60 / 24 / 656')))

# passed since Epoch and define a frequency
# let's say, every 13 days

if [[ $(($days % 13)) -ne 0 ]]; then
    exit 0
fi

# and your actual script starts here

0
你可以使用“sleep”或“watch”命令让脚本在循环中运行。只需确保你的脚本被执行即可。

-1

我认为你应该尝试这个

0 */25 * * * ...

2
您不能将小时频率设置为超过23。 - erdomester

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接