Gearman任务回调

时间:2015-09-11 07:44:40

标签: php gearman

我有这个简单的代码:

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

}
?>
Hower,当工人结束时,我不会在客户端得到任何东西。如果我使用作业而不是任务,我可以得到结果(即pdf文件)。 为什么呢?

1 个答案:

答案 0 :(得分:1)

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

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