Can make a PHP script work forever with Cron Job?

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

I'm going to create a PHP web server, so will this script work forever with Curl?

+5
source share
4 answers

Remember to set the maximum execution time to infinite (0).

It’s better to make sure that you do not run more than one instance if this is 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  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 web server you can run one that should work endlessly like this (instead of using cURL, this removes the 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 can start with linux cron using wget as follows:

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

Or you can start with Windows Scheduler using bitadmin, which launches a .bat file that contains the following:

bitsadmin /create infiniteloop
bitsadmin /addfile infiniteloop http://localhost/infinite_loop.php
bitsadmin /resume infiniteloop
+15
source

php- ff.:

  • set_time_limit(0);// php , ,
  • [ script ] . setInterval(), setTimeout()

EDIT: cron, .

EDIT: , , , , . , cron, . [edit] , @Tiberiu-Ionuţ Stan, cron.

+1

, PHP . .: http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time

, set_time_limit script (http://php.net/manual/en/function.set-time-limit.php).

, PHP ( HTTP-) . script, , .

If your site is being viewed by other users, you can do this on every page.

(And imagine if someone requests a script more than once, you will have several instances of running it)

0
source

You can only do this if you set set_time_limit (0) in your script, otherwise it will stop executing after max_execution_time in the configuration.

And you use a while (true) condition that will make your script run always.

0
source

All Articles