Executing a shell command in the background

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
daven
Forum Contributor
Posts: 332
Joined: Tue Dec 17, 2002 1:29 pm
Location: Gaithersburg, MD
Contact:

Executing a shell command in the background

Post by daven »

I need to delay execution of a command for several minutes after a user enters a page (ex--user enters page, 5 minutes later command executes). The problem with using sleep() is that the page will not load until the delay is over. The unix sleep command has similar problems. So what I need is to have sleep and the following command be executed directly on the server, so my page will load. Ideas?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

you might try to detach the command from the (virtual) console by appending a &, e.g. exec('updatedb&'); to update the locate-db in background. Never tried this with php but it might work....
User avatar
DesignerSMS
Forum Newbie
Posts: 17
Joined: Tue Aug 06, 2002 12:16 am
Location: Gold Coast, Australia

Post by DesignerSMS »

Yes, this will work.

In your PHP script for generating the page use something like this:

Code: Select all

<?php
  exec("php -q scriptname.php > /dev/null &");
?>
NB: The output of the script must be redirected to something other than STDOUT

And then in scriptname.php:

Code: Select all

<?php
  sleep(60 * 5); // 5 minutes
  /* Execute script contents here */
?>
If this is a popular site this type of execution method could potentially use up a lot of resources. If you get even say 10 requests for this page a second, after 5 minutes there would be 3,000 PHP processes sleeping.
Post Reply