Gearman 任务回调

Gearman Tasks Callback

我有这个简单的代码:

<?php
$client = new GearmanClient();

// Add a server
$client->addServer(); // by default host/port will be "localhost" & 4730

echo "Sending job\n";

// 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());
}

?>

和一名工人:

<?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;