0

Is it possible, on a website/webserver (having full root access) to run a PHP script which calls mysql queries in the background. What I mean with that:

An user clicks to process something - however to prevent the user waiting for running the query it should look like it is done for the user - he doesn't has to wait for the PHP/MYSQL in the browser However the script should be running on the server and finish

How can I do that? If there is none effective solution in PHP - is it possible with other languages?

I'm not talking about cron jobs - I'm on a ubuntu machine (no windows)

Would be for running many PHP scripts (all the same) in the background - Nginx be the better solution or Apache? Is it even relevant?

8
  • 1
    The solution is Ajax, it basically javascript who trigger some PHP. Jul 31, 2014 at 13:52
  • you can also run cron jobs in ubuntu/whatever linux. The question is how the users should get data from them when using a browser.. you would need to save this precalculated data somewhere and output it in another webserver based script... is that what you are trying to do?
    – Olli
    Jul 31, 2014 at 13:53
  • 1
    Like @ArthurBALAGNE said: AJAX
    – GuyT
    Jul 31, 2014 at 13:57
  • 1
    if the user doesn't need to close the page after he clicks, you may use asyncronous ajax requests. An asyncronous request will also allow you to tell the user when all the queries are done :). Check api.jquery.com/jquery.ajax if you're using jQuery
    – briosheje
    Jul 31, 2014 at 13:59
  • 1
    Does the browser user need to see the result of this background execution?
    – RiggsFolly
    Jul 31, 2014 at 14:01

1 Answer 1

4

The best architecture I could recommend here is probably a queue/worker setup. For instance, this is simple to do with Gearman (alternatively: ØMQ, RabbitMQ or similar advanced queues). You spin up a number of workers which run in the background and can handle the database query (I'm partial to daemonizing them with supervisord). Spin up as many as you want to support running in parallel; since the job is apparently somewhat taxing, you want to carefully control the number of running workers. Then any time you need to run this job, you fire off an asynchronous job for the Gearman workers and then return immediately to your user. The workers will handle the request whenever they get around to do it. This assumes you don't need any particular feedback for the user, that the job can simply finish whenever without anybody needing to know about it immediately.

If you do need to provide user feedback when the job is finished, you may simply want to try to execute the request via AJAX. For really sophisticated setups and realtime feedback, you may use the Gearman approach with feedback delivered via a pub/sub websocket. That's quite an involved setup though.

Not the answer you're looking for? Browse other questions tagged or ask your own question.