如何使用 anacron 与 cron 来执行 cron 错过的任务?

如何使用 anacron 与 cron 来执行 cron 错过的任务?

我的 Python 脚本需要每天下午 2 点运行。另一个 Python 脚本必须每天晚上 9 点运行。为了实现这一点,我设置了 2 个 cronjobs 来在给定时间运行这些脚本:

0 14 * * * python /home/user/unban.py
0 21 * * * python /home/user/ban.py

我知道,要成功运行 cron,我的机器必须全天候运行。那么,如果在安排 cronjobs 时机器处于离线状态,我该如何使用 anacron 运行脚本呢?

答案1

man anacrontab

期限以天为单位,延迟以分钟为单位。

不幸的是,这意味着 anacron 不适合确定跳过的每小时工作。

考虑在脚本中添加更多时间逻辑并将其变为单个脚本:

// NOT REAL CODE. Just an example of the logic.
currently_banned = am_I_banned?()    
if 14 <= current_time().hour <= 21
    if currently_banned is True:
        unban()
    else:
        do_nothing()
else:
    if currently_banned is False:
        ban()
    else:
        do_nothing()

您可以将单个脚本放入 cron.hourly 中,并在启动时运行该脚本。请记住将脚本添加到您的常规备份模式中。

或者,您可以使用 systemd 计时器/服务组合来触发该作业,就像系统上所有其他定期服务一样。Systemd 还可以在重启时触发脚本,Systemd 有一个学习曲线,但我发现学习非常值得。

相关内容