每天上午 10 点到晚上 11 点之间通过 cron 随机运行一次 Python 脚本

每天上午 10 点到晚上 11 点之间通过 cron 随机运行一次 Python 脚本

我在 ubuntu 上,需要每天上午 10 点到晚上 11 点之间随机运行一次 python 脚本。现在我只让它在固定的时间运行,我见过一些例子,但主要是在一个时间范围内执行重复性任务,而我每天只需要一次。

关于最好的方法是什么有什么想法吗?

亲切的问候!

答案1

我不知道cron支持随机开始时间。

但是您可以利用at安排python脚本在随机时间运行:

0 10 * * * echo '"/path/to/my_script.py"' | at "now + $(shuf -i 1-780 -n 1)min"

与我之前使用的解决方案相比,这有一个好处sleep,即它将在重新启动之间保留。

您可以检查atq作业安排的时间。

答案2

根本不要使用 cron。系统定时器为此有一个内置选项,称为RandomizedDelaySec

RandomizedDelaySec=
   Delay the timer by a randomly selected, evenly distributed amount of time between 0
   and the specified time value. Defaults to 0, indicating that no randomized delay shall
   be applied. Each timer unit will determine this delay randomly before each iteration,
   and the delay will simply be added on top of the next determined elapsing time, unless
   modified with FixedRandomDelay=, see below.

因此,就您而言,您将有一个带有OnCalendar=*-*-* 10:00:00RandomizedDelaySec=46800(= 13 小时)的计时器。看这篇关于 Ask Ubuntu 的文章或者Arch Linux 维基有关设置 systemd 计时器的更多详细信息。

答案3

将作业安排在每天早上 10:00,并让作业休眠一段随机时间(0 秒到 46800 秒之间)。

这里唯一的问题是我们不能这样做,sleep "$(( RANDOM % 46800 ))"因为 shell 的RANDOM变量(至少在 的情况下bash)采用 0 到 32767 之间的值,这个值太小了。

相反,我们可以使用awk

awk 'BEGIN { srand(); print int(46800*rand()) }'

这意味着我们可以使用以下时间表:

0 10 * * * sleep "$( awk 'BEGIN { srand(); print int(46800*rand()) }' )" && mypythonscript

另一种方法是无论如何使用RANDOM变量,但要得到分钟而不是距离它几秒钟。您感兴趣的时间跨度正好是 780 分钟,因此您可以使用

SHELL=/bin/bash

0 10 * * * sleep "$(( 60*(RANDOM % 780) ))" && mypythonscript

这意味着你的 python 脚本只会在一整分钟内启动,除非你使用RANDOM 再次60以上随机化为(RANDOM % 60).

相关内容