linux - Linux 的 crontab 天异常(exception)

标签 linux cron

我有一个从周一到周五运行的 crontab 作业,但我需要它对特定日期进行异常(exception)处理,例如 1 月 1 日、4 月 11 日等。

如何在我的 crontab 作业中异常(exception)?

* * * * 1-5 ./full-backup

最佳答案

最简单的方法是使用 andor 列表序列。

man sh: AND and OR lists are sequences of one of more pipelines separated by the && and || control operators, respectively. AND and OR lists are executed with left associativity.

An AND list has the form command1 && command2. command2 is executed if, and only if, command1 returns an exit status of zero.

An OR list has the form command1 || command2. command2 is executed if and only if command1 returns a non-zero exit status.

如果您想从 cron 中排除 2 天,比如说 1 月 1 日和 4 月 11 日,那么您可以执行以下操作:

# .---------------- 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
  *  *  *  * 1-5    [ `date '+\%m\%d'` == "0101" ] || [ `date '+\%m\%d'` == "0411" ] || ./full_backup.sh

从您有更多天数排除的那一刻起,它就变得有点棘手。您可以使用较小的脚本,例如 excludedaycmd

#!/usr/bin/env bash
while [[ $1 != "" ]]; do
  [[ $(date "+%m%d" )) == $1 ]] && exit 1
  shift
done
exit 0

如果该脚本的任何参数适合一天,则该脚本将以 1 退出。你的 cron 看起来就像这样。

# .---------------- 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
  *  *  *  * 1-5    excludedaycmd 0101 0411 && ./full_backup.sh

任何其他脚本也可以以任何其他形式使用。

关于linux - Linux 的 crontab 天异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48818748/

相关文章:

linux - 如何使用 sed 用反斜杠替换字符串模式

linux - Docker 命令挂起而没有响应

从 crond 启动时出现 PHP 段错误

python - 如何手动清理主目录中的 conda?

Visual Studio 上的 C 或 C++

c - 内核如何检测内核空间段错误?

Bash 脚本到 scp 远程服务器目录中的最新文件

python - Cron 作业在使用 python 3.7 的 GAE 上 60 秒后以 504 网关超时结束

node.js - 如何在 Linux Ubuntu 中将 NodeJS 应用程序作为 crontab 运行?

PHP Laravel 任务调度最佳实践