Search code examples
phpcallbackbackground-processgearman

Gearman addTaskBackground complete callback does not fire


I am trying to run some job in background and write the result to file result from complete callback, but it does only work for addTask (not in background) and not for addTaskBackground.

Does someone have an idea?

$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() . "\n", 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() . "\n";
        break;
    }
};

function uploader($job){

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

Solution

  • CompleteCallback will not be called on background task completion. If you want to check the status of background job use 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] . "\n";
    

    Read more here