0

I am creating a pdf report of some 100 pages using shell script mode of wkhtmltopdf. Now, the thing is that the script takes a whole lot of time to create the report and save it in the specified path.

Currently, I am calling the script like this:

$stmt = $sh_script.' > /dev/null 2>/dev/null &';
shell_exec($stmt);

Doing this causes the shell to run in background and the report gets generated, but on the browser end after sometime I see

504 Gateway Time-out
nginx/1.4.6 (Ubuntu)

Which is not a very comfortable message, I want to call the shell_exec statement in an asynchronous way so that it is called and php code moves on. Can someone help me with this?

Ankit Singh
  • 594
  • 4
  • 16

2 Answers2

2

So before I give you a recommended solution for your question, I want to add really quick that I would probably find a php library which can achieve what you are looking to do, instead of executing shell commands from PHP, which can be a bad idea for many reasons, but if you intend on going that route, please look at this answer for some advice on security when executing shell commands via PHP:

https://stackoverflow.com/a/4535900/4660602

Now, to get back to your answer, anytime you are executing a big task in PHP that requires some extra time, it is never really a good idea to keep the user waiting at the browser. That is where building a Queue can become crucial to your application. You begin to work on some task AFTER you explain to your user via your user interface that the work is being done in the background and they will be notified when it is completed, etc.

There are ways to create a queue WITHOUT using 3rd party software, but there are some excellent tools out there such as RabbitMQ, IronMQ or Beanstalkd which can be extremely helpful to performing tasks in the background. These services push your task into a queue and these items in the queue are processed in a timely manner, but the user does not have to wait for a response until it finishes working, hence no more 504 timeouts.

OR you could try a much dirtier solution and just increase the script timeout value in php and on your server, but this can have some unexpected results. For nginx & for Apache

Best of luck!

Community
  • 1
  • 1
Geoherna
  • 3,523
  • 1
  • 24
  • 39
  • Nice insight George, I will look into RabbitMQ and setup a RabbitMQ server if we(company) face more such performance bottlenecks. – Ankit Singh Jun 16 '16 at 20:08
0

You're close .. But you want nohup (No hang up) and your statment at the end should look more like /dev/null 2>&1 &

That said .. I believe this should work:

exec('nohup' . $sh_script . ' > /dev/null 2>&1 &')

Zak
  • 6,976
  • 2
  • 26
  • 48
  • It didn't work out. The behaviour is still the same, the script works but the browser shows 504 Gateway Time-out. – Ankit Singh Jun 16 '16 at 20:03