1

I am creating a small plugin get get's data from different websites. The data does not have to be up to date, and I do not want to use a cronjob for this.

Instead with every visit of the website I want to check if the DB needs updating. Now it takes a while before the whole db is updated, and I do not want the user waiting for that.

Is there a way that I can have the function fired, but in the background. The user will just work as normal, but in the background the db is updating.

Saif Bechan
  • 16,551
  • 23
  • 83
  • 125
  • Will the user need any information from the script? That is, will it eventually return anything to the user? If not, simply use the `exec()` function and execute a script on the server. – Griffin Nov 10 '11 at 18:07
  • No the user does not need to get anything. He will just get the data that is currently available. – Saif Bechan Nov 10 '11 at 18:13

3 Answers3

1

You'd want to use exec() with a command that redirects output to a file or /dev/null, otherwise PHP will wait for the command to complete before continuing with the script.

exec('/path/to/php /path/to/myscript.php 2>&1 > /dev/null');
Steve Lewis
  • 1,302
  • 7
  • 8
1

There are many solutions to execute a PHP code asynchronously. The simplest is calling shell exec asynchronously Asynchronous shell exec in PHP. For more sophisticated true parallel processing in PHP try Gearman. Here a basic example on how to use Gearman.

The idea behind Gearman is you will have a deamon what will manage jobs for you by assigning tasks to worker. You will write two PHP files:

  1. Worker: Which contain the code you want to run asynchronously.
  2. Client: The code that will call your asynchronous function.
Community
  • 1
  • 1
Laith Shadeed
  • 4,271
  • 2
  • 23
  • 27
1

You could also fork the process using pcntl_fork

As you can see in the php.net example you get two execution threads following the function call. The parent thread could complete as usual, while the child could go on doing its thing

jlb
  • 19,090
  • 8
  • 34
  • 65
  • Thanks, this seems a much better solution actually than the exec(). I need to work with the database, I think If I use the exec I have to do all the dbconnection again. Creating a seperate thread sounds better. – Saif Bechan Nov 10 '11 at 18:24