Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Long Running Background Task

Tags:

php

background

I am currently trying to generate an epub on demenad from content that is available to me. Unfortunately, when there is alot of content for the epub, it takes a while (10 mins in some cases) for the http request to complete - which is not ideal

I want to follow an approach similar to that of Safari - Generate an epub and email the user when the document is available

My question is - what is the best way for running a background task/thread in PHP that could take a long time to complete

like image 910
Damien Avatar asked Dec 10 '12 14:12

Damien


Video Answer


2 Answers

You want to be careful with long-running PHP processes as, for one PHP is not very memory efficient (as an example an array of just 100 ints in PHP can consume as much as 15KB of memory). This is normally fine for 99% of the use cases since most people are just using PHP for websites and those processes run for fractions of a second so memory is sacrificed for speed. However, for a long-running process (especially if you have a lot of them) this may not be your best solution.

You also want to be very careful calling exec/shell_exec like functions in PHP as they are internally implemented as streams (i.e. they can cause blocking in the parent process as it normally has to wait on the stream to return data).

One option to background the task is to use fork. However, I strongly suggest using a proper job manager like gearman (see php extensions also), or queue, like amqp or zmq, to handle these tasks more cleanly. Which one is more suitable for your use case, I'll let you decide.

like image 74
Sherif Avatar answered Nov 15 '22 18:11

Sherif


you can run the command

$command = 'nohup >/dev/null 2>&1 /your/background/script.php &'
like image 34
silly Avatar answered Nov 15 '22 19:11

silly