2

I have a PHP page that read and write some data in a database. Is there any way that I can run the PHP page on the server automatically (not by the request of client) every n seconds?

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
Faridzs
  • 672
  • 8
  • 23
  • 2
    Take a look at cron jobs if you're on linux or Windows Task Scheduler if you're on you guess it ... – HamZa May 18 '13 at 18:19
  • 3
    There's Cron job (http://en.wikipedia.org/wiki/Cron) – Ofir Baruch May 18 '13 at 18:19
  • Every n seconds is possible, but it is usually unnecessary. Cron can be run only with a granularity of a minute. What's your use-case for the frequency you specify? – halfer May 18 '13 at 18:33
  • there is a set of calculations that are needed to be done, and its important how much time has past from the last time. – Faridzs May 18 '13 at 18:42
  • 1
    That doesn't explain why it needs to be so frequent. You can still work out "how much time has past from the last time" if your run frequency is ten minutes. – halfer May 19 '13 at 13:33
  • Nor does it explain why it can't be handled synchrnously from the php page. – symcbean May 20 '13 at 11:47

3 Answers3

5

Rather than having cronjob, it might be easier/more efficient to just have a 'daemon' style script.

A script that is always running, and just does something at set intervals.

<?php
    while(true) {
        do_stuff();
        sleep(30);
    }

(More efficent, because the script doesn't need to do a full start up every time it's run. It can hold configuration etc, between calls to do_stuff.)

How to run process as background and never die?

Of course 'do_stuff()' might actually just be calling another script

function do_stuff() {
    file_get_contents('http://example.com/scripts/calc.php');
}
Community
  • 1
  • 1
barryhunter
  • 20,886
  • 3
  • 30
  • 43
  • Yes, although the OP would additionally need to consider how to restart it at reboot. – halfer May 19 '13 at 13:32
  • To whoever edited the reply, set_time_limit is not actully needed, because scripts run on via CLI dont have a time limit. And yes, there are a number of ways the script could be run, to ensure it always running. – barryhunter May 20 '13 at 10:26
  • Well I was actully trying to be tactful by deliberately not naming names. – barryhunter May 20 '13 at 11:12
2

Depending on your flavor of Linux you’ll need to setup a cronjob.

See here for a little walk-through: http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/

Phillip Berger
  • 2,317
  • 1
  • 11
  • 30
0

If your job can be run every X minutes, then you should register a cron job (I'm assuming you're using a linux server). Open the console and type:

$crontab -e

Then add this line:

*/10 * * * * php /home/yourdir/the-script.php

This will invoke the script every 10 minutes. I'm not positive if you need to use absolute file path, but that's what I do and it works :)

Nenad Mitic
  • 577
  • 4
  • 12