Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a php script to run forever with Cron Job?

Tags:

php

<?php
 while(true){
 //code goes here.....
 }
  ?>

I want to make a PHP web server, so how can I make this script run forever with Curl?

like image 309
cdxf Avatar asked Jun 21 '12 06:06

cdxf


2 Answers

Don't forget to set maximum execution time to infinite(0).

Better make sure you don't run more than one instance, if that's your intention:

ignore_user_abort(true);//if caller closes the connection (if initiating with cURL from another PHP, this allows you to end the calling PHP script without ending this one)
set_time_limit(0);

$hLock=fopen(__FILE__.".lock", "w+");
if(!flock($hLock, LOCK_EX | LOCK_NB))
    die("Already running. Exiting...");

while(true)
{

    //avoid CPU exhaustion, adjust as necessary
    usleep(2000);//0.002 seconds
}

flock($hLock, LOCK_UN);
fclose($hLock);
unlink(__FILE__.".lock");

If in CLI mode, just run the file.

If in another PHP on a webserver, you could start the one which must run infinetely like this (instead of using cURL, this eliminating a dependency):

$cx=stream_context_create(
    array(
        "http"=>array(
            "timeout" => 1, //at least PHP 5.2.1
            "ignore_errors" => true
        )
    )
);
@file_get_contents("http://localhost/infinite_loop.php", false, $cx);

Or you could start from linux cron using wget like this:

`* * * * * wget -O - http://localhost/infinite_loop.php`

Or you could start from Windows Scheduler using bitsadmin running a .bat file which contains this:

bitsadmin /create infiniteloop
bitsadmin /addfile infiniteloop http://localhost/infinite_loop.php
bitsadmin /resume infiniteloop
like image 90
Tiberiu-Ionuț Stan Avatar answered Oct 23 '22 04:10

Tiberiu-Ionuț Stan


For a php code to run forever, it should have the ff.:

  • set_time_limit(0); // so php won't terminate as normal, if you will be doing stuff that will take a very long processing time
  • handler for keeping the page active [usually by setting up a client-side script to call the same page in intervals] See setInterval(), setTimeout()

EDIT: But since you will be setting up a cron job then you can keep away from the client-side handling.

EDIT: My suggestion, is not to use infinite loops unless you have a code that tells it to exit the loop after some time. Remember, you will be calling the same page using a cron job, so there is no point in keeping the loop infinite. [edit] Otherwise, you will be needing a locking system as suggested by @Tiberiu-Ionuț Stan so only 1 instance may run each time the cron job is called.

like image 40
Dexter Huinda Avatar answered Oct 23 '22 03:10

Dexter Huinda