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!
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.
Nice chart but:
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.