user3745117
user3745117

Reputation: 127

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. 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. 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

Is there a way to modify the current while loop so that I may achieve this? Thanks!

Upvotes: 0

Views: 102

Answers (3)

user3442743
user3442743

Reputation:

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.

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.

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

Upvotes: 1

cujo
cujo

Reputation: 378

There are much better ways to do this because PHP requires and HTTP request to run that file.

  1. Run a cron job to run this request every set interval (not recommended)
  2. Use another program like python which can run a daemon to do this
  3. Do the calculation every time the page is requested (recommended and almost always possible)

Upvotes: 0

Sankalp Bhatt
Sankalp Bhatt

Reputation: 1204

The right way to do such kind of things is via "Cron Job".

The software utility Cron is a time-based job scheduler in Unix-like computer operating systems. 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.

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

Useful Source: How to get a unix script to run every 15 seconds?

Upvotes: 0

Related Questions