简体   繁体   English

每小时随机执行一次Cron作业

[英]Running a cron job randomly for every one hour

I want a cronjob to run every one hour randomly. 我希望cronjob随机每隔一小时运行一次。 (ie if the first job runs at 58 minutes,the second job should run at 47 minutes and the third one at 52 minutes and so on) But this should run randomly for everyone hour. (即,如果第一份作业运行58分钟,第二份作业应运行47分钟,第三份作业应运行52分钟,依此类推),但这应该在每个小时内随机运行。 Is there a way to do this? 有没有办法做到这一点?

Instead of using perl or even php, just use the BASH $RANDOM built in divided by 3600 which equals one hour like so. 除了使用perl甚至不使用php之外,只需使用内置的BASH $ RANDOM除以3600,即等于一小时。

0 * * * * sleep $((RANDOM%3600)) && /path/to/yourScript

Keep in mind that you will probably have some race conditions with a script sleeps randomly close to an hour depending on how long it takes for your script to execute. 请记住,您的脚本可能会在某些竞争条件下随机睡眠近一个小时,具体取决于脚本执行所需的时间。

You could run a job every hour, on the hour, that sleeps up to 3,599 seconds and then executes your script: 您可以每小时运行一个小时的作业,该作业休眠3,599秒,然后执行脚本:

0 * * * * /path/to/perl -e 'sleep int rand 3600' && /path/to/yourScript

Or, using PHP if you prefer that to Perl : 或者,如果您更喜欢Perl ,则使用PHP

0 * * * * /path/to/php -r 'sleep(rand(0,3599));' && /path/to/yourScript

You can find the path to Perl with: 您可以通过以下方式找到Perl的路径:

which perl

likewise for PHP : 对于PHP同样如此:

which php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM