我想知道它是否L是 Debian 的 cron 实现中允许的特殊字符之一?我正在尝试设置一个 cron 在每个月的最后一天运行。
“L”代表“最后”。当在星期字段中使用时,它允许您指定结构,例如给定月份的“最后一个星期五”(“5L”)。在 day-of-month 字段中,它指定该月的最后一天。
注意:L 是一个非标准字符,只存在于一些 cron 实现中(Quartz java scheduler)
如果没有,您将如何设置一个 cron 在每个月的最后一天运行?您会在 stackoverflow 上推荐 3 个像此解决方案这样的不同条目吗?
crontab 手册页 ( man 5 crontab)中描述了 Debian 上的 Cron 条目。Debian 使用 Vixie 的 cron,他的手册页说:
The crontab syntax does not make it possible to define all possible
periods one could image off. For example, it is not straightforward to
define the last weekday of a month. If a task needs to be run in a spe-
cific period of time that cannot be defined in the crontab syntaxs the
best approach would be to have the program itself check the date and
time information and continue execution only if the period matches the
desired one.
If the program itself cannot do the checks then a wrapper script would
be required. Useful tools that could be used for date analysis are ncal
or calendar For example, to run a program the last Saturday of every
month you could use the following wrapper code:
0 4 * * Sat [ "$(date +%e)" = "`ncal | grep $(date +%a | sed -e 's/.$//')
| sed -e 's/^.*\s\([0-9]\+\)\s*$/\1/'`" ] && echo "Last Saturday" &&
program_to_run
Run Code Online (Sandbox Code Playgroud)
所以沿着这些路线工作:
0 0 * * * perl -MTime::Local -e
'exit 1 if (((localtime(time()+60*60*24))[3]) < 2);' || program_to_run
Run Code Online (Sandbox Code Playgroud)
我从未L在 Linux cron 实现中看到过。
要在一个月的最后一天运行作业,请在实际天数的超集上运行它并检查第二天的日期。使用 GNU date,您可以date -d tomorrow用来显示第二天的日期,因此请检查它是否仍在同一个月内。为避免在夏令时开始或结束的一天中的几个位置出现问题,请指定一天中不是凌晨的时间(示例中为 12:00/中午)。请记住,这%在 crontab中很特殊,需要用反斜杠保护。
42 1 28-31 * * if [ "$(date -d 'today 12:00' +\%m)" != "$(date -d 'tomorrow 12:00' +\%m)" ]; then last_day_of_month_job; fi
Run Code Online (Sandbox Code Playgroud)
您可以对一个月中一周中特定日期的最后一次出现应用相同的技术。每周运行该作业,并仅在下一次发生在不同月份时才触发它。
42 1 * * 3 if [ "$(date -d 'today 12:00' +\%m)" != "$(date -d 'now + 7 days 12:00' +\%m)" ]; then last_wednesday_of_month_job; fi
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20938 次 |
| 最近记录: |