Wednesday, May 29, 2013

asynchronous php thread (asynchronous cake shell execution)

While cumbersome if not impossible to actually manage threads in PHP, you can always execute in background a php script.

Here's how:

While in a cakephp framework method (of course the important details are the ones in colored background):

$str = 'path/to/cakelib/cake/console/cake -working '.ROOT . DS . APP_DIR.' -app ' . ROOT . DS . APP_DIR . ' my_shell_script > /dev/null 2> '.LOGS.'my_log.log &';

exec($str, $output2, $status);




I used the ideas from this post: http://stackoverflow.com/questions/222414/asynchronous-shell-exec-in-php

This answer:
If it "doesn't care about the output", couldn't the exec to the script be called with the & to background the process?
EDIT - incorporating what @AdamTheHut commented to this post, you can add this to a call to exec:
"> /dev/null 2>/dev/null &"
That will redirect both stdio (first >) and stderr (2>) to /dev/null and run in the background.
There are other ways to do the same thing, but this is the simplest to read.

An alternative to the above double-redirect:
" &> /dev/null &"


No comments:

Post a Comment