tags:

views:

37

answers:

3

I'd like to trigger a script to update some statistics when a user submits a new record, but I don't want the user to have to wait for the script to finish before being redirected.

>-- Time -->
                        > redirect User -> User Does Stuff -> more stuff -> etc
                       /                   
User Input -> Submit ->
                       \
                        > updating stats in background -> Possibly still running

What's the best way to do this in PHP?

EDIT for Fabrik

Users would like to see immediate feedback reflecting the addition of their new data, but this new data only comes in 2 or 3 times a day, so I think an interval-based CRON job might be an unnecessary use of server resources and also fail to satisfy their need for urgency. Hope this helps!

A: 

Nice chart but:

  • We need to know more about your needs (e.g. is it possible to use cron or we need to display the stats asap?)
  • If you can use cron set up a small interval (5 mins) then poll your database for changes
  • If you can't use cron try to build your site fully with AJAX so you can safely run background processes
fabrik
+1  A: 

I did a quick google search for php background process and most of the hits are suggesting using either exec or shell_exec to call the script you want to run in the background.

Edit: This article seems to be the most relevant to your question.

captaintokyo
+1  A: 

If you just need a small code snippet i'd go for something like this:

<?php
if($new_record) {
  exec("php /path/updateStats.php ".escapeshellarg($userid)." >/dev/null &");
  your_redirect_call_etc();
}

redirecting the output stream and the '&' will lead to the exec call running independently from the the script.

If you need a bigger / scaleable solution you could look into something like Gearman which would allow you to run those background jobs on another server easily / controlled.

edorian