Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gearman & PHP: Proper Way For a Worker to Send Back a Failure

Tags:

php

gearman

The PHP docs are a bit fuzzy on this one, so I'm asking it here. Given this worker code:

<?php
$gmworker= new GearmanWorker();
$gmworker->addServer();
$gmworker->addFunction("doSomething", "doSomethingFunc");
while($gmworker->work());

function doSomethingFunc()
{
    try {
        $value = doSomethingElse($job->workload());
    } catch (Exception $e) {
        // Need to notify the client of the error
    }

    return $value;
}

What's the proper way to notify the client of any error that took place? Return false? Use GearmanJob::sendFail()? If it's the latter, do I need to return from my doSomethingFunc() after calling sendFail()? Should the return value be whatever sendFail() returns?

The client is using GearmanClient::returnCode() to check for failures. Additionally, simply using "return $value" seems to work, but should I be using GearmanJob::sendData() or GearmanJob::sendComplete() instead?

like image 299
mellowsoon Avatar asked Feb 28 '11 15:02

mellowsoon


1 Answers

This may not the be the best way to do it, but it is the method i have used in the past and it has worked well for me.

I use sendException() followed by sendFail() in the worker to return a job failure. The exception part is optional but i use it so the client can error and know roughly why it failed. After the sendFail I return nothing else. As an example this is a the method that the worker registers as the callback for doing work:

public function doJob(GearmanJob $job)
{
    $this->_gearmanJob = $job;


    try{
        //This method does the actual work
        $this->_doJob($job->functionName());
    }
    catch (Exception $e) {
        $job->sendException($e->getMessage());
        $job->sendFail();
    }
}

After sendFail() do not return anything else, otherwise you may get strange results such as the jobserver thinking the job ended ok.

As regards returning data, i use sendData() if i am returning data in chunks (such as streaming transcoded video, or any 'big' data where i don't want to move around one large blobs) at various intervals during my job with a sendComplete() at the end. Otherwise if I only want to return my data in one go at the end of the job I only use sendComplete().

Hope this helps.

like image 130
James Butler Avatar answered Nov 04 '22 06:11

James Butler