Reputation: 2783
I'm running a CLI script that mostly sleeps. Every 10 seconds or so the script executes something. The problem is, the script is sitting at 94% CPU usage while sleeping.
The way I set it up is:
while(1){
sleep(10);
doStuff();
}
While this works as intended, there's an obvious problem. In C++/Java I could simply set a timer which would eliminate the looping problem. Also, I was hoping I wouldn't need cron jobs.
Is there any alternative way to do this?
Apparently my original script (which was fairly large) never actually entered sleep mode, so the while loop ran uniterupted and burned CPU cycles. For anyone who has the same issue, make sure that is not the case with you!
Upvotes: 6
Views: 6637
Reputation: 2783
My script was setup something like this:
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.
}
}
The problem was, the script kept setting $sleep
to false
, which meant it never entered sleep mode and used up nearly 100% CPU.
Upvotes: 1
Reputation: 163232
In the past, when I've needed to make a PHP script a daemon, I've used the PEAR module outlined here: http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/
If you don't want to use the PEAR module, you can examine its source code and do something similar.
Upvotes: 3