Skip to content

Instantly share code, notes, and snippets.

@juneym
Created September 14, 2013 04:07
Show Gist options
  • Save juneym/6558745 to your computer and use it in GitHub Desktop.
Save juneym/6558745 to your computer and use it in GitHub Desktop.
PHP Gearman Worker (non-blocking) -- based on the PHP doc.
<?php
declare(ticks = 1);
$terminate = false;
pcntl_signal(SIGTERM, function() use (&$terminate) {
$terminate = true;
echo "Terminating = true \n";
});
echo "Starting\n";
# Create our worker object
$worker= new GearmanWorker();
# Make the worker non-blocking
$worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);
$worker->setTimeout(2000);
# Add the default server (localhost, port 4730)
$worker->addServer("127.0.0.1", 4730);
# Add our reverse function
$worker->addFunction('reverse', 'reverse_fn');
# Try to grab a job
while (!$terminate && (@$worker->work() ||
$worker->returnCode() == GEARMAN_IO_WAIT ||
$worker->returnCode() == GEARMAN_NO_JOBS ||
$worker->returnCode() == GEARMAN_TIMEOUT)
) {
echo "return code " . $worker->returnCode() . "\n";
if ($worker->returnCode() == GEARMAN_SUCCESS) {
continue;
}
echo "[ " . date("Y-m-d H:i:s") . " ] Waiting for next job...\n";
if (!@$worker->wait())
{
if ($worker->returnCode() == GEARMAN_NO_ACTIVE_FDS)
{
# We are not connected to any servers, so wait a bit before
# trying to reconnect.
sleep(5);
continue;
}
elseif ($worker->returnCode() == GEARMAN_TIMEOUT)
{
echo "Timedout. Retrying \n";
sleep(1);
continue;
}
break;
}
echo "return code " . $worker->returnCode() . "\n";
echo "-----------\n";
}
echo "Worker Error: " . $worker->error() . "\n";
function reverse_fn($job)
{
sleep(5);
return strrev($job->workload());
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment