PHP sleep () causes high CPU usage

I am running a CLI script that is basically sleeping. Every 10 seconds or so, the script executes something. The problem is that the script sits at 94% of the CPU during sleep.

How I installed it:

while(1){
    sleep(10);
    doStuff();
}

Although this works as intended, there is an obvious problem. In C ++ / Java, I could just set a timer that will fix the loop problem. Also, I was hoping that I would not need cron jobs.

Is there an alternative way to do this?


Update

Apparently, my original script (which was rather large) never went into sleep mode, so the while loop executed single and burned CPU cycles. For those who have the same problem, make sure it is not!

+5
source share
2 answers

script - :

define('THREAD_SLEEP', 10); // Sleep time
$sleep = false; // Skips the first sleep

while(1){
    if($sleep){
        sleep(THREAD_SLEEP);
    }

    $sleep = true; // By default, the script enters sleep mode each loop.

    if(doSomethingAndHaveMoreToDo()){
        $sleep = false; // If more stuff to do, remove sleep and keep doing it.
    }
}

, script $sleep false, , 100% CPU.

+1

All Articles