PHP 8.3.4 Released!

GearmanClient::addTaskBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskBackgroundAjoute une tâche d'arrière-plan pour une exécution en parallèle

Description

public GearmanClient::addTaskBackground(
    string $function_name,
    string|int|float $workload,
    mixed $context = null,
    ?string $unique_key = null
): GearmanTask|false

Ajoute une tâche d'arrière-plan pour une exécution en parallèle d'autres tâches. Appelez cette méthode pour toutes les tâches à exécuter en parallèle, puis, appelez la méthode GearmanClient::runTasks() pour réaliser les tâches.

Liste de paramètres

function_name

Une fonction enregistrée que le travailleur va exécuter

workload

Données sérialisées à analyser

context

Contexte de l'application à associer avec une tâche

unique_key

Un identifiant unique utilisé pour identifier une tâche particulière

Valeurs de retour

Un objet GearmanTask ou false si la tâche n'a pu être ajoutée.

Exemples

Exemple #1 2 tâches dont une en arrière-plan

Cet exemple montre la différence entre l'exécution en arrière-plan et une exécution normale. Le client ajoute 2 tâches qui doivent exécuter la même fonction, mais une a été ajoutée avec la méthode addTaskBackground(). Une fonction de rappel est définie afin de surveiller la progression du travail. Un agent simple avec un délai artificiel rapporte la progression et le client la traite via la fonction de rappel. 2 agents sont exécutés dans cet exemple. Notez que la tâche en arrière-plan n'est pas affichée par le client.

<?php

# Le script client

# Crée un client Gearman
$gmc= new GearmanClient();

# Ajoute un serveur de travaux par défaut
$gmc->addServer();

# Définit 2 fonctions de rappel afin de surveiller la progression
$gmc->setCompleteCallback("reverse_complete");
$gmc->setStatusCallback("reverse_status");

# Ajoute une tâche pour la fonction "reverse"
$task= $gmc->addTask("reverse", "Hello World!", null, "1");

# Ajoute une autre tâche, mais cette fois, en arrière-plan
$task= $gmc->addTaskBackground("reverse", "!dlroW olleH", null, "2");

if (!
$gmc->runTasks())
{
echo
"ERREUR " . $gmc->error() . "\n";
exit;
}

echo
"FAIT\n";

function
reverse_status($task)
{
echo
"STATUT : " . $task->unique() . ", " . $task->jobHandle() . " - " . $task->taskNumerator() .
"/" . $task->taskDenominator() . "\n";
}

function
reverse_complete($task)
{
echo
"TERMINÉ : " . $task->unique() . ", " . $task->data() . "\n";
}

?>
<?php

# Le script de l'agent

echo "Début\n";

# Crée un agent.
$gmworker= new GearmanWorker();

# Ajoute un serveur par défaut (localhost).
$gmworker->addServer();

# Enregistre la fonction "reverse" sur ce serveur.
$gmworker->addFunction("reverse", "reverse_fn");

print
"Attente d'un travail...\n";
while(
$gmworker->work())
{
if (
$gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo
"return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function
reverse_fn($job)
{
echo
"Travail reçu : " . $job->handle() . "\n";

$workload = $job->workload();
$workload_size = $job->workloadSize();

echo
"Charge de l'agent : $workload ($workload_size)\n";

# Cette boucle n'est pas nécessaire, mais permet de comprendre le fonctionnement
for ($x= 0; $x < $workload_size; $x++)
{
echo
"Envoi du statut : " . ($x + 1) . "/$workload_size complete\n";
$job->sendStatus($x+1, $workload_size);
$job->sendData(substr($workload, $x, 1));
sleep(1);
}

$result= strrev($workload);
echo
"Résultat : $result\n";

# On retourne au client ce que l'on veut.
return $result;
}

?>

L'agent affiche, pour les 2 travaux :

Travail reçu : H:foo.local:65
Charge de l'agent : !dlroW olleH (12)
1/12 complete
Travail reçu : H:foo.local:66
Charge de l'agent : Hello World! (12)
Envoi du statut : 1/12 complete
Envoi du statut : 2/12 complete
Envoi du statut : 2/12 complete
Envoi du statut : 3/12 complete
Envoi du statut : 3/12 complete
Envoi du statut : 4/12 complete
Envoi du statut : 4/12 complete
Envoi du statut : 5/12 complete
Envoi du statut : 5/12 complete
Envoi du statut : 6/12 complete
Envoi du statut : 6/12 complete
Envoi du statut : 7/12 complete
Envoi du statut : 7/12 complete
Envoi du statut : 8/12 complete
Envoi du statut : 8/12 complete
Envoi du statut : 9/12 complete
Envoi du statut : 9/12 complete
Envoi du statut : 10/12 complete
Envoi du statut : 10/12 complete
Envoi du statut : 11/12 complete
Envoi du statut : 11/12 complete
Envoi du statut : 12/12 complete
Envoi du statut : 12/12 complete
Résultat : !dlroW olleH
Résultat : Hello World!

Affichage du client :

STATUT : 1, H:foo.local:66 - 1/12
STATUT : 1, H:foo.local:66 - 2/12
STATUT : 1, H:foo.local:66 - 3/12
STATUT : 1, H:foo.local:66 - 4/12
STATUT : 1, H:foo.local:66 - 5/12
STATUT : 1, H:foo.local:66 - 6/12
STATUT : 1, H:foo.local:66 - 7/12
STATUT : 1, H:foo.local:66 - 8/12
STATUT : 1, H:foo.local:66 - 9/12
STATUT : 1, H:foo.local:66 - 10/12
STATUT : 1, H:foo.local:66 - 11/12
STATUT : 1, H:foo.local:66 - 12/12
TERMINÉ : 1, !dlroW olleH
FAIT

Voir aussi

add a note

User Contributed Notes 3 notes

up
17
Anonymous
8 years ago
It is unlikely this example works quite as advertised.

The foreground job will block, however the background job should not.. (and if it does that's not documented Gearman behaviour far as I know and would not make sense for a Background job).

So, if the foreground job completes, then we would expect runTasks() to return at that moment, regardless of the status of the background job(s). With nothing else to do, the php script (the client) in this example would exit at that point.

To fully-utilize background jobs, it's reasonable to assume that we still wish to know their status. To do that, you need a polling loop that "checks up on them" and waits until their completion.

That eliminates the point of background jobs of course - because the client would still be Blocking (in a polling loop) more or less occupied, and unable to exit/finish.

So, in practice, background jobs mean you are decoupled from the client upon execution (because the main point is to free up the client, otherwise just use foreground execution), which means the client is likely going to exit, meaning the jobs themselves should be reporting their status and final result independently, not leaving it up to the client.

It's a significantly different setup compared to foreground jobs. In fact this example is kind of silly to even mix the two.

Nobody will ever see this post, because apparently nobody in the world has ever commented on the php gearman client, but it's a good post never the less.
up
2
iunknowvb at gmail dot com
6 years ago
function run_process($cmd,$outputFile = '/dev/null', $append = false){
$pid=0;
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
$cmd = 'wmic process call create "'.$cmd.'" | find "ProcessId"';
$handle = popen("start /B ". $cmd, "r");
$read = fread($handle, 200); //Read the output
$pid=substr($read,strpos($read,'=')+1);
$pid=substr($pid,0,strpos($pid,';') );
$pid = (int)$pid;
pclose($handle); //Close
}else{
$pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $cmd, ($append) ? '>>' : '>', $outputFile));
}
return $pid;
}
function is_process_running($pid){
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
//tasklist /FI "PID eq 6480"
$result = shell_exec('tasklist /FI "PID eq '.$pid.'"' );
if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
return true;
}
}else{
$result = shell_exec(sprintf('ps %d 2>&1', $pid));
if (count(preg_split("/\n/", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {
return true;
}
}
return false;
}
function stop_process($pid){
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
$result = shell_exec('taskkill /PID '.$pid );
if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
return true;
}
}else{
$result = shell_exec(sprintf('kill %d 2>&1', $pid));
if (!preg_match('/No such process/', $result)) {
return true;
}
}
}
$cmd='';
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
$cmd= $php_path.'\php.exe '.$path.'\long_process.php' ;
}else{
$cmd='/usr/bin/php -f /var/www/example.com/public/long_process.php';
}

$pid=run_process($cmd);
up
-2
raitech at gmail dot com
8 years ago
This method seems only useful when you doesn't need to know something about the worker, when you can let runTasks() finishes its code and destroy the GearmanClient object without a problem.

If you need to get data from worker via callbacks, forget it after runTasks() finishes.

You have to block your execution in the GearmanClient "main loop", so it can call the callbacks. It seems that runTasks() is that "main loop".
To Top