문제

public GearmanTask GearmanClient::addTask  ( string $function_name  , string $workload  [, mixed &$context  [, string $unique  ]] )
public bool GearmanWorker::addFunction  ( string $function_name  , callback $function  [, mixed &$context  [, int $timeout  ]] )

These are class methods that can be used to integrate the two. With these, how do you relate the workload with the called function?

도움이 되었습니까?

해결책

GearmanClient is used to submit a task. Normally this is done from a web page, or a script meant to read a list of tasks to be submitted.

GearmanWorker is meant to be set up in such a way that many parallel 'workers' can be run at the same time. Logically, whatever a worker does should represent a single atomic unit of work. That can mean doing a single transformation of an object into another and saving it back to the database, or assembling and sending an html email for a single user. $function_name is a function that takes a single argument, which is a GearmanJob object.

So, your controller script might look something like this.

  $gearman_params = json_encode( array(
      'id'       => 77,
      'options'  => array('push' => true),
  ) );
  $client = new GearmanClient();
  $client->doBackground( "widgetize", $gearman_params );

Then, your worker will do something like this.

$gmworker  = GearmanWorker;
$gmworker->addFunction( "widgetize", "widgetize" );
while( $gmworker->work() ) {  

if ( $gmworker->returnCode() !== GEARMAN_SUCCESS ) {
    echo "Worker Terminated." . PHP_EOL ;
    break;
  }

} // while *working*

function widgetize( $job ) {
    $workload = json_decode( $job->workload() );

    /* do stuff */
}

A few things to keep in mind:

  • The worker script is designed to be long running script, hence the while loop. Make sure to set your timeout and memory limits appropriately.
  • It's also good practice to give the worker a run limit. As in, only allow the worker to run a few times, and then exit; PHP still sucks with memory usage, and it can be hard to tell when a worker will be killed because it ran out of memory.
  • In the same vein it's also best to design workers to be idempotent, so jobs can be resubmitted to workers if they fail.
  • The Client can submit jobs to the worker with different priorities, and they don't neccessarily have to be run in the background, like the above example. They can be run so that the client blocks.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top