Gearman addTaskBackround完整回调不会触发

2022-05-24 00:00:00 background-process callback php gearman

我正尝试在后台运行一些作业,并将结果写入来自完整回调的结果文件,但它仅对addTask(不在后台)有效,对addTaskBackground无效。

有人有主意吗?

$client = new GearmanClient();

$client->addServer('localhost');

$client->setCompleteCallback("complete");
$client->addTaskBackground('upload', 'http://youtube.com/watch?v=o3mP3mJDL2k', null, 1);
$client->addTaskBackground('upload', 'http://www.youtube.com/watch?v=SgAVnlnf8w0', null, 2);

/* in these case complete callback works
$client->addTask('upload', 'http://youtube.com/watch?v=o3mP3mJDL2k');
$client->addTask('upload', 'http://www.youtube.com/watch?v=SgAVnlnf8w0');
*/

$client->runTasks();

function complete($task){
    file_put_contents('/home/vonica/public_html/test/tmp/1.txt', $task->unique() . ", " . $task->data() . "
", FILE_APPEND);
}

$worker = new GearmanWorker();
$worker->addServer('localhost');

$worker->addFunction('upload', 'uploader');

while($worker->work()){
    if ($worker->returnCode() != GEARMAN_SUCCESS) {
        echo "ret code: " . $worker->returnCode() . "
";
        break;
    }
};

function uploader($job){

   $content = $job->workload();
   exec ('echo $( youtube-dl -f worst "'.$content.'")');
   return $content;
}

解决方案

CompleteCallback不会在后台任务完成时调用。如果要检查后台作业的状态,请使用GearmanClient::jobStatus

Client.php

// save this $job_handle somewhere
$job_handle = $client->doBackground('upload', 'http://youtube.com/watch?v=o3mP3mJDL2k', null, 1);

status.php

// use previously saved job handle to check job's status
$job_handle = $_GET['job_handle'];
$stat = $client->jobStatus($job_handle);
echo "Running: " . 
     ($stat[1] ? "true" : "false") . 
     ", numerator: " . 
     $stat[2] . 
     ", denomintor: " . 
     $stat[3] . "
";

阅读更多内容here

相关文章