Gearman任务回调



我有这个简单的代码:

<?php
$client = new GearmanClient();
// Add a server
$client->addServer(); // by default host/port will be "localhost" & 4730
echo "Sending jobn";
// Send job
$data = file_get_contents('test.html');
$client->addTask("convert", $data,null,1);
$client->setCompleteCallback("complete");
$client->runTasks();
if (! $client->runTasks())
{
    echo "ERROR " . $client->error() . "n";
    exit;
}
else
{
}
function complete($task) {
  echo "Success: $task->unique()n";
  echo($task->data());
}
?>

和一个worker:

<?php
// Create our worker object
$worker = new GearmanWorker();
// Add a server (again, same defaults apply as a worker)
$worker->addServer();
// Inform the server that this worker can process "reverse" function calls
$worker->addFunction("convert", "convertToPDF");

while (1) {
  print "Waiting for job...n";
  $ret = $worker->work(); // work() will block execution until a job is delivered
  if ($worker->returnCode() != GEARMAN_SUCCESS) {
    break;
  }
}
function convertToPDF(GearmanJob $job) {
  $workload = $job->workload();
  $fd = fopen("temp.html", 'wr');
  fwrite($fd,$workload);
  exec('wkhtmltopdf temp.html test.pdf');
  $job->sendData(file_get_contents('test.pdf'));
  return file_get_contents('test.pdf');
}
?>

然而,当worker结束时,我在客户端中没有得到任何东西。如果我使用工作而不是任务,我可以得到结果(即pdf文件)。为什么?

您应该在添加任务之前设置完整回调。

// Send job
$data = file_get_contents('test.html');
$client->setCompleteCallback("complete");
$client->addTask("convert", $data,null,1);
$client->runTasks();

exec('wkhtmltopdf temp.html test.pdf');
$job->sendComplete(file_get_contents('test.pdf'));
return GEARMAN_SUCCESS;

最新更新