Uncaught Gearman Exception

Posted on: October 20th, 2013 by taff No Comments

Using an older version of the most excellent Gearman (0.8.1), I came across a phenomena that wouldn't let me catch the ErrorException. Because I couldn't upgrade due to compatibility issues I had find the workaround.

Gearman Timeout Exception

The Gearman Timeout Exception occurred when the worker wasn't running when the runTasks() method was called. I thought I could prevent my worker file from expiring by using set_time_limit = 0; Unfortunately it didn't. So these were the problems that I faced:

  • Uncaught Gearman Exception setTimeout
  • Someway to reinstantiate the client worker, ideally when the exception happen
  • A cronjob to periodically check if the GearmanWorker is working

The Uncaught Gearman Exception

Although was initially the largest problem, it was in fact the easiest to solve by redefining the set_error_handler like so:

set_error_handler( array($this, 'gearman_error_handler'), -1 & ~E_NOTICE & ~E_USER_NOTICE);
//reset error handler.

public function gearman_error_handler($errno, $errstr, $errfile, $errline) {
if ($errno == 2) {
echo("A search went wrong");
} else {
$_log = \Logger::getInstance("preisvergleich_gearman_worker");
echo("A search went wrong because the Gearman Workers weren't running";

The last line resets back to the default error handling class that is implemented by the application

Reinstantiate the Gearman Client

I found something on StackOverflow that got me thinking. Why not build a class to monitor the Gearman Worker? In particularly as I had more that one worker running, albeit for different tasks, being able to check if the task was running would also come in handy for the cronjob check. Using shell_exec I was then able to restart the worker by executing the php file if and when the worker dies on me again.
That obviously goes a bit beyond catching Gearman Exceptions but could well be around in another blog post if someone finds it of interest. This is the method that I used:

protected static function callWorkerFile($strPathToWorker) {
 return shell_exec("nohup php " . $strPathToWorker . " > /dev/null & echo $!");

Leave a Reply