Skip to content

Instantly share code, notes, and snippets.

@hjr3
Created September 3, 2011 21:05
Show Gist options
  • Save hjr3/1191796 to your computer and use it in GitHub Desktop.
Save hjr3/1191796 to your computer and use it in GitHub Desktop.
Gearman worker addTasks example
// macro.php
<?php
$gmw = new GearmanWorker();
$gmw->addServer();
$gmw->addFunction('macro', function(GearmanJob $job) {
$gmc = new GearmanClient;
$gmc->addServer();
$gmc->setCompleteCallback(function(GearmanTask $task) {
$h = $task->jobHandle();
echo "Job '{$h}' complete", PHP_EOL;
});
$gmc->setFailCallback(function(GearmanTask $task) {
$h = $task->jobHandle();
echo "Job '{$h}' failed", PHP_EOL;
});
$gmc->addTask('micro', 'pass');
$gmc->addTask('micro', 'pass');
$gmc->addTask('micro', 'pass');
$gmc->addTask('micro', 'fail');
$gmc->addTask('micro', 'fail');
$gmc->addTask('micro', 'fail');
$gmc->runTasks();
});
while ($gmw->work());
?>
// micro.php
<?php
$gmw = new GearmanWorker;
$gmw->addServer();
$gmw->addFunction('micro', function(GearmanJob $job) {
if ($job->workload() == 'fail') {
$job->sendFail();
} else {
$job->sendComplete('complete');
}
});
while ($gmw->work());
?>
// cli
gearman -f macro -s
@stevenscg
Copy link

Do you know if the sendComplete or sendFail calls are required for the callbacks to receive data?

It appears from testing that they are required, but the PHP manual examples (1) seem to demonstrate the callback without explicitly calling sendComplete (for example).

(1) http://www.php.net/manual/en/gearman.examples-reverse-task.php

@hjr3
Copy link
Author

hjr3 commented Jan 13, 2012

I don't think sendComplete is required. The following works fine for me:

<?php

$gmw = new GearmanWorker;

$gmw->addServer();

$gmw->addFunction('echo', function(GearmanJob $job) {
    $job->sendData($job->workload());
});

while ($gmw->work());

@stevenscg
Copy link

So the companion client to the "echo" worker above would have to register a setDataCallback method to receive the object sent through the sendData call, right?

Similarly, the worker should call sendComplete if the client is expecting something via setCompleteCallback.

I don't do many callbacks with Gearman, but the manual really failed to make the connection for me. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment