cron作业和随机时间,给予小时内 [英] Cron jobs and random times, within giving hours

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

问题描述

我需要在完全随机的时间运行PHP脚本每天20次的能力。我也希望它只是早上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作业。虽然我不能够产生任何的bash脚本。

I'm familiar with creating cron jobs in linux. Although I'm not able to create any bash scripts.

推荐答案

如果我明白你在找什么,你需要做的事情有点乱,就像运行了一个随机化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

和中/路径/要/ 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点之间50400秒,它会是一个有点复杂随机化秒为好。最后,由于启动时间是随机的,相互独立的,这是可能的(但不是很可能),该脚本的两个或更多个实例将同时启动。

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天全站免登陆