1

I am trying to run a PHP script every 2 seconds but i can only set a cron job for every minute.

I had the idea of using a for loop in PHP and running my code inside the loop X amount of times and the cron job then runs every minute but i don't know how long my script will take to run so it may not finish when the cron job restarts.

whats the best way to run it every 2 seconds?

2 Answers2

4

create a daemon.

e.g. daemon.php

which would do:

while(true){
    sleep(2);

    /* do your magic */

}

then launch it as a background task

php -q daemon.php&
jancha
  • 4,873
  • 1
  • 21
  • 35
  • He already said: `I had the idea of using a for loop in PHP and running my code inside the loop X amount of times and the cron job then runs every minute but i don't know how long my script will take to run so it may not finish when the cron job restarts.` Your solution is not valid for him. – Javier Provecho Fernández Mar 31 '14 at 08:55
  • 1
    @JavierProvechoFernández You did not understand janchas approach. The deamon is started manually and not by the cronjob. Once it started it will run all the time in the background (unless the running condition fails or the deamon is stopped manually) and there is no need for a cronjob anymore. That does not make his solution, but your comment invalid. What I also find pretty cool is iron.io's worker: http://www.iron.io/worker. Especially for large sclaed apps. – thpl Mar 31 '14 at 08:59
  • Using http://fat-controller.sourceforge.net might help with daemonising, make it more stable and make it easier to recover from errors. – SlappyTheFish Mar 31 '14 at 09:05
  • He doesnt know how much time will take to execute his script. So if you want to exactly see my answer. – Javier Provecho Fernández Mar 31 '14 at 09:07
0

This is not the best way to aproach a problem like yours, but this is your answer:

for($i = 0; $i < 30; $i++){
    sleep(2);
    exec("php name.php > /dev/null 2>/dev/null &");
}

The for will run your program 30 times each 2 secconds. You must setup a cronjob of 1 minute for the source code above. The exec("php name.php > /dev/null 2>/dev/null &"); make sure PHP dont wait for ending the program, so every two secconds you will execute your task.

You can also follow jancha answer but modified like this:

while(true) {
    sleep(2);
    exec("php name.php > /dev/null 2>/dev/null &");
}

Then launch it as a background task:

php -q daemon.php&