10

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?

mellowsoon
  • 22,273
  • 19
  • 57
  • 75
  • It should be noted that you can only retrieve this information with normal tasks (`GearmanClient::do()`), not background tasks `GearmanClient::doBackground()`). See also: http://stackoverflow.com/a/11631673/664108 – Fabian Schmengler Feb 02 '13 at 16:36

1 Answers1

9

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.

James Butler
  • 3,852
  • 1
  • 26
  • 38
  • Using gearman to stream video sounds awesome. Would love to know more about your software's architecture... – Alexander Trauzzi Sep 10 '13 at 19:29
  • 1
    @Omega it wasn't video streaming in the usual sense of viewing video, but chunked transcoding for storage somewhere else. Also - it's certainly not how I would do it these days either :-) – James Butler Sep 17 '13 at 00:03
  • @JamesButler how would you do it these days? – dre Apr 19 '14 at 17:26