4

I have a problem with Gearman and the worker for PHP. I want to run the same function at the same time. But now Gearman seems to make it a queue.

The output I'm searching for is:

$ ./daemon.php  
Starting daemon...
Received job: H:www-dev1:15 
Received job: H:www-dev1:16 
Finished
Finished

But the output of current code is:

$ ./daemon.php  
Starting daemon...
Received job: H:www-dev1:15 
Finished
Received job: H:www-dev1:16 
Finished

Is there possible to fork GearmanWorker using pcntl_fork()?

Client:

$client = new GearmanClient();
$client->addServer();

$args = array('test' => 'test1');
$args = serialize($args);

$client->doBackground('test', $args);
sleep(1);
$client->doBackground('test', $args);

echo "Done";

Worker:

#!/usr/bin/php
<?php

echo "Starting daemon..." . PHP_EOL;

$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction('test', 'testFunc');

while ($worker->work()) {
}

function testFunc($job) {

    echo "Received job: " . $job->handle() . PHP_EOL;
    sleep(10);
    echo "Finished" . PHP_EOL;  
}
jeni
  • 442
  • 1
  • 4
  • 12
brasimon
  • 769
  • 2
  • 9
  • 22

2 Answers2

5

One worker can handle one job at one time. If you need to execute more than one job, you need to create more than one worker of course. in your case just execute the "Worker"-script multiple times and put them in the background. Or (as you mentioned yourself) create forks, but the first one is definetly easier ;)

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • Great answer, it's right on point and touches some of the less documented need to knows.. – Mike Mackintosh Feb 07 '13 at 20:32
  • I use Supervisor (in Ubuntu) to make sure multiple instances of my Gearman workers are always running. – Gabe Spradlin Sep 05 '14 at 05:49
  • @Gabe Spradlin, correct me if I'm wrong, but here conversation is about php, not nodejs's supervisor module – Velaro May 03 '18 at 11:45
  • @Velaro I was referring to the Supervisor program which on Linux allows you to manage any program you want to run as a daemon. You can define how many instances you want to run, how many times the program should restart before it is considered failed, etc. See http://supervisord.org/ – Gabe Spradlin May 03 '18 at 16:12
  • @Gabe Spradlin, Oh, thank you for your nice response! – Velaro May 04 '18 at 09:06
-1

you can try worker clone function to create more workers

GearmanWorker::clone(void)
jeni
  • 442
  • 1
  • 4
  • 12