从某个日期开始每天 运行 的 Cron 表达式

Cron expression to run every day starting from a date

我需要一个 cron 表达式,它会从 2016 年 1 月 25 日开始每天中午 12 点触发。这就是我想出的:

0 0 12 25/1 * ? *

但在 1 月 31 日之后,下一次发射时间是 2 月 25 日。

是否有用于执行此操作的 cron 表达式?如果不能,我可以使用什么?

假设您希望在 1 月 25 日之后永远 运行 这个过程(即 2032 年,届时服务器可能已经被替换),我会用三个表达式来实现:

0 0 12 25-31 1 * 2016  command # Will run the last days of Jan 2016 after the 25th
0 0 12 * 2-12 * 2016   command # Will run the rest of the months of 2016
0 0 12 * * * 2017-2032 command # will run for every day of years 2017 and after.

希望对您有所帮助。

有多种方法可以完成此任务,一种可能是 运行使用 cron 作业和测试条件编写脚本,如果为真 运行 实际上需要脚本,否则跳过。

这是一个例子,

20 0 * * * home/hacks/myscript.sh

并在 myscript.sh 中将您的代码用于测试条件和 运行 实际 command/script

下面是此类脚本的示例,

#!/bin/bash

if( ( $(date) <= "31-01-2016" ) || ( $(date) >= "25-02-2017" ) ){

   // execute your command/script
}else {
     // do Nothing
}

您可以编写一个日期表达式,它只匹配特定时间点之后的日期;或者你可以为你的脚本创建一个包装器,如果当前日期早于主脚本应该 运行

的时间,它就会中止
#!/bin/bash
# This is GNU date, adapt as required for *BSD and other variants
[[ $(date +%s -d 2018-02-25\ 00:00:00) > $(date +%s) ]] && exit
exec /path/to/your/real/script "$@"

...或者您可以使用 at.

安排添加此 cron 作业
at -t 201802242300 <<\:
schedule='0 0 12 25/1 * ? *'   # update to add your command, obviously
crontab=$(crontab -l)
case $crontab in
    *"$schedule"*) ;;          # already there, do nothing
    *) printf "%s\n" "$crontab" "$schedule" | crontab - ;;
esac
:

(未经测试,但你明白了。我只是 copy/pasted 你的时间表达式,我想它对 crontab 不是真的有效。我假设 Quartz 有办法做类似的事情。)

at 的时间规范很奇怪,我设法让它在 Mac 上运行,但在 Linux 上可能会有所不同。请注意,我在前一天晚上 23:00 将其设置为 运行,即计划的第一次执行前一小时。

这是我的回答 here 的简短副本。 最简单的方法是使用一个额外的脚本来进行测试。你的 cron 看起来像:

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed
  0  12  *  *  *  daytestcmd 1 20160125 && command1
  0  12 *  *  *   daytestcmd 2 20160125 && command2

这里,command1将从2016-01-25开始每天执行。 command2从2016-01-25开始每隔一天执行一次

daytestcmd 定义为

#!/usr/bin/env bash
# get start time in seconds
start=$(date -d "${2:-@0}" '+%s')
# get current time in seconds
now=$(date '+%s')
# get the amount of days (86400 seconds per day)
days=$(( (now-start) /86400 ))
# set the modulo
modulo=
# do the test
(( days >= 0 )) && (( days % modulo == 0))