我有两个工人同时工作,目前他们都在同一时间接受相同的工作。我给人的印象是,当工作人员A运行作业时,工作人员B将在队列中接收下一个作业。每个作业大约需要10秒钟才能完成。我该怎么做?
我已将代码简化为:(假设客户端两次相隔两次被调用两次)
客户
$client = new GearmanClient();
$client->addServer();
$client->doBackground("my_task");
工作者
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction("my_task", "my_task_fn");
while($worker->work());
function my_task_fn($job) {
echo $job->handle(); // both workers show same job #, I want each worker getting a different job
sleep(10);
}
答案 0 :(得分:1)
您所描述的内容不应该发生,我提供了一个示例供您了解。直到工作人员响应并返回响应,客户端脚本才会完成。但是您可以通过将'doNormal'更改为'doBackground'来轻松适应。在您的worker函数中放置一个睡眠计数器以减慢该worker的速度,并使您的客户端处于循环状态以创建大量作业,以查看该进程的工作进展情况。
客户代码
// Create our client object
$client = new GearmanClient();
// Add a server
$client->addServer(); // by default host/port will be "localhost" & 4730
echo "Sending job\n";
// Send reverse job
$result = $client->doNormal("reverse", "Hello!");
if ($result) {
echo "Success: $result\n";
}
工人代码
// Create our worker object
$worker = new GearmanWorker();
// Add a server (again, same defaults apply as a worker)
$worker->addServer();
// Inform the server that this worker can process "reverse" function calls
$worker->addFunction("reverse", "reverse_fn");
while (1) {
print "Waiting for job...\n";
$ret = $worker->work(); // work() will block execution until a job is delivered
if ($worker->returnCode() != GEARMAN_SUCCESS) {
break;
}
}
// A much simple reverse function
function reverse_fn(GearmanJob $job) {
$workload = $job->workload();
echo "Received job: " . $job->handle() . "\n";
echo "Workload: $workload\n";
$result = strrev($workload);
echo "Result: $result\n";
return $result;
}