Cron jobs and random times, within giving hours

最近给 Dota 圣剑传说 添加一个随机活动,每小时里在聊天室生成一个 黄金巨龙来袭事件。从 stackoverflow 找来一个方法如下:

http://stackoverflow.com/questions/9049460/cron-jobs-and-random-times-within-giving-hours

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:

1
0 9 * * * /path/to/bashscript

and in /path/to/bashscript:

1
2
3
4
5
6
7
#!/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

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.

文章目录
|