Cron 作业和随机时间,在给定的时间内 [英] Cron jobs and random times, within given hours

查看:28
本文介绍了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 作业.

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:

定时任务:

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