简体   繁体   English

如何为bash脚本指定运行时间?

[英]How to specify run timing for bash scripts?

I was looking for a way to continuously run a PHP script every 15 seconds online, so that I may manage some accounts using an API. 我一直在寻找一种方法,可以每15秒钟在线一次连续运行PHP脚本,以便可以使用API​​管理一些帐户。 I was able to find a script that satisfies what I was looking for as follows: 我能够找到一个满足以下需求的脚本:

#!/bin/bash
#This script runs every 15 seconds
#This script is ran in /etc/rc.local (startup)

while (sleep 15 && php test.php) &
do
    wait $!
done 

This script works perfectly and runs every 15 seconds. 该脚本可以完美运行,每15秒运行一次。 However, now I want to modify the script such that it may 但是,现在我想修改脚本,以便它可能

  1. do what the script is already doing 做脚本已经在做的
  2. run a second script, every 5 minutes 每5分钟运行第二个脚本

Is there a way to modify the current while loop so that I may achieve this? 有没有办法修改当前的while循环,以便实现这一目标? Thanks! 谢谢!

If you really want to use a loop 如果您真的想使用循环

Runs forever until you terminate it, although yours also does. 永远运行直到您终止它,尽管您也这样做。

Change sleep to whatever interval you want, i just set it to 1 for this example. 将睡眠更改为您想要的任何间隔,在本示例中,我将其设置为1。

Set up if statements and use modulus to set the time frame for each one, also probably want to set count back to 0 in the highest timed if to stop it getting too large. 设置if语句并使用模数为每个时间框架设置时间范围, if要阻止计数过大,也可能希望在最高定时将计数设置回0

You can add as many as you want for as many times as you want :) 您可以根据需要添加任意数量的次数:)

#!/bin/bash

while (true)
do
    sleep 1
    if (( count % 15 == 0 )) ;then
            php test.php
    fi
    if (( count % 300 == 0 )); then
            SecondScript
            count=0
    fi

     (( count = count +1 ))


done

The right way to do such kind of things is via "Cron Job". 做这类事情的正确方法是通过“ Cron Job”。

The software utility Cron is a time-based job scheduler in Unix-like computer operating systems. 软件实用程序Cron是类似Unix的计算机操作系统中的基于时间的作业调度程序。 People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. 设置和维护软件环境的人员使用cron安排作业(命令或shell脚本)以固定的时间,日期或间隔定期运行。

source: http://en.wikipedia.org/wiki/Cron 来源: http : //en.wikipedia.org/wiki/Cron

Useful Source: How to get a unix script to run every 15 seconds? 有用的资料: 如何使Unix脚本每15秒运行一次?

There are much better ways to do this because PHP requires and HTTP request to run that file. 有更好的方法来执行此操作,因为PHP需要和HTTP请求才能运行该文件。

  1. Run a cron job to run this request every set interval (not recommended) 运行cron作业以每设置一个间隔运行此请求(不建议)
  2. Use another program like python which can run a daemon to do this 使用另一个可以运行守护程序的程序(例如python)来执行此操作
  3. Do the calculation every time the page is requested (recommended and almost always possible) 每次请求页面时进行计算(推荐,几乎总是可能的)

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

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