Basic Gearman client and worker, background

例1 Basic Gearman client and worker, background

This example shows a very simple client and worker. The client sends a string to the job server as a background job, and the worker reverses the string. Note that since the work is performed asynchronously, the client does not wait for the job to complete and exits (and hence the client never receives the results).

<?php

# create our client object
$gmclient= new GearmanClient();

# add the default server (localhost)
$gmclient->addServer();

# run reverse client in the background
$job_handle $gmclient->doBackground("reverse""this is a test");

if (
$gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo 
"bad return code\n";
  exit;
}

echo 
"done!\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse""reverse_fn");

print 
"Waiting for job...\n";
while(
$gmworker->work())
{
  if (
$gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo 
"return_code: " $gmworker->returnCode() . "\n";
    break;
  }
}

function 
reverse_fn($job)
{
  echo 
"Received job: " $job->handle() . "\n";

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

  echo 
"Workload: $workload ($workload_size)\n";

  
# This status loop is not needed, just showing how it works
  
for ($x0$x $workload_size$x++)
  {
    echo 
"Sending status: " . ($x 1) . "/$workload_size complete\n";
    
$job->sendStatus($x$workload_size);
    
sleep(1);
  }

  
$resultstrrev($workload);
  echo 
"Result: $result\n";

  
# Return what we want to send back to the client.
  
return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return 
strrev($job->workload());
}

?>

上の例の出力は、 たとえば以下のようになります。

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:41
Workload: this is a test (14)
1/14 complete
2/14 complete
3/14 complete
4/14 complete
5/14 complete
6/14 complete
7/14 complete
8/14 complete
9/14 complete
10/14 complete
11/14 complete
12/14 complete
13/14 complete
14/14 complete
Result: tset a si siht
% php reverse_client_bg.php
done!

関連キーワード:  complete, worker, Basic, job, reverse, string, local, Received, Waiting, Starting