在指定的小时内执行Cron工作和随机时间 [英] Cron jobs and random times, within given hours

查看:393
本文介绍了在指定的小时内执行Cron工作和随机时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够每天完全随机地运行20次PHP脚本.我也希望它仅在上午9点至晚上11点之间运行.

I need the ability to run a PHP script 20 times a day at completely random times. I also want it to run only between 9am - 11pm.

我熟悉在Linux中创建cron作业的情况.

I'm familiar with creating cron jobs in linux.

推荐答案

如果我了解您要查找的内容,则需要做一些杂乱的事情,例如拥有运行随机化bash脚本的cron作业运行时间...是这样的:

If I understand what you're looking for, you'll need to do something a bit messy, like having a cron job that runs a bash script that randomizes the run times... Something like this:

crontab:

0 9 * * * /path/to/bashscript

以及/path/to/bashscript中的

and in /path/to/bashscript:

#!/bin/bash

maxdelay=$((14*60))  # 14 hours from 9am to 11pm, converted to minutes
for ((i=1; i<=20; i++)); do
    delay=$(($RANDOM%maxdelay)) # pick an independent random delay for each of the 20 runs
    (sleep $((delay*60)); /path/to/phpscript.php) & # background a subshell to wait, then run the php script
done

一些注意事项:这种方法会浪费一些资源,因为它会在上午9点启动20个后台进程,每个后台进程会随机等待几分钟(最多14小时,即晚上11点),然后启动php脚本并退出.另外,由于它使用随机数分钟(而不是秒),因此开始时间并不是很随机.但是$ RANDOM仅增加到32,767,并且从上午9点到晚上11点之间有50,400秒,随机分配秒也要复杂一点.最后,由于开始时间是随机的并且彼此独立,因此有可能(但不太可能)同时启动两个或更多脚本实例.

A few notes: this approach it a little wasteful of resources, as it fires off 20 background processes at 9am, each of which waits around for a random number of minutes (up to 14 hours, i.e. 11pm), then launches the php script and exits. Also, since it uses a random number of minutes (not seconds), the start times aren't quite as random as they could be. But $RANDOM only goes up to 32,767, and there are 50,400 seconds between 9am and 11pm, it'd be a little more complicated to randomize the seconds as well. Finally, since the start times are random and independent of each other, it's possible (but not very likely) that two or more instances of the script will be started simultaneously.

这篇关于在指定的小时内执行Cron工作和随机时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆