3

In a apcahe server i want to run a PHP scripts as cron which starts a php file in background and exits just after starting of the file and doesn't wait for the script to complete as that script will take around 60 minutes to complete.how this can be done?

vinay035
  • 31
  • 3
  • 6
  • 1
    Just run your script on cron every minute. You can create some analog of "mutex" on a file and check if previous instance finished. Apache has nothing to do with your task. – zysoft Sep 09 '12 at 17:55
  • Why cant you just "run" the cron? Its a cron job - so you dont need to wait for it to finish? – Laurence Sep 09 '12 at 17:56

3 Answers3

10

You should know that there is no threads in PHP. But you can execute programs and detach them easily if you're running on Unix/linux system.

$command = "/usr/bin/php '/path/to/your/php/to/execute.php'";
exec("{$command} > /dev/null 2>&1 & echo -n \$!");

May do the job. Let's explain a bit :

exec($command); 

Executes /usr/bin/php '/path/to/your/php/to/execute.php' : your script is launched but Apache will awaits the end of the execution before executing next code.

> /dev/null

will redirect standard output (ie. your echo, print etc) to a virtual file (all outputs written in it are lost).

2>&1

will redirect error output to standard output, writting in the same virtual and non-existing file. This avoids having logs into your apache2/error.log for example.

&

is the most important thing in your case : it will detach your execution of $command : so exec() will immediatly release your php code execution.

echo -n \$!

will give PID of your detached execution as response : it will be returned by exec() and makes you able to work with it (such as, put this pid into a database and kill it after some time to avoid zombies).

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
2

You need to use "&" symbol to run program as background proccess.

$ php -f file.php &

Thats will run this command in background.

You may wright sh script

#!/bin/bash
php -f file.php &

And run this script from crontab.

MrSil
  • 608
  • 6
  • 12
1

This may not be the best solution to your specific problem. But for the record, there is Threads in PHP.

https://github.com/krakjoe/pthreads

I'm assuming you know how to use threads, this is very young code that I wrote myself, but if you have experience with threads and mutex and the like you should be able to solve your problem using this extension.

This is clearly a shameless plug of my own project, and if the user doesn't have the access required to install extensions then it won't help him, but many people find stackoverflow and it will solve other problems no doubt ...

John Conde
  • 217,595
  • 99
  • 455
  • 496
Joe Watkins
  • 17,032
  • 5
  • 41
  • 62