PHP code example of many / gearman

1. Go to this page and download the library: Download many/gearman library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

many / gearman example snippets


           
           public function fire($job, $data)
            {
                $result=$data[0] + $data[1];
                //模拟任务消耗时间
                sleep(2);
                echo "Client results:{$result}\n";
                return $result;
            }
        
        

        
            public function seedWork()
                {
                    $sum = 0;
                    //实例化gearman服务的客户端
                    $client = new GearmanClient();
                    //默认参数主机地址:127.0.0.1 端口:4730
                    $config = config('queue.gearman');
                    if (isset($config['hosts'])) {
                        foreach ($config['hosts'] as $server) {
                            $client->addServer($server['host'], $server['port']);
                        }
                    } else {
                        $client->addServer($config['host'], $config['port']);
                    }
            
                    //可以通过setCompleteCallback函数给计算结果返回给客户端
                    $client->setCompleteCallback(function (GearmanTask $task) use (&$sum) {
                        $sum = $task->data();
                        $this->info("Server results:" . $sum . "\n");
                    });
            
                    for ($i = 0; $i < 2; $i++) {
                        //后期版本会封装单独的类来匹配数据项
                        $data = [
                            "displayName" => "App\\Services\\SumServer",
                            "job" => "App\\Services\\SumServer",
                            "maxTries" => null,
                            "timeout" => null,
                            "data" => [1 + $i, 2 + $i]
                        ];
                        //添加任务
                        $client->addTask('default', json_encode($data, 1));
                    }
                    //添加任务
            
                    $client->runTasks();
                }
        


    namespace App\Services;

    class SendMail {

        public function fire($job, $data)
        {
            mail('[email protected]', 'gearman test', $data['message']);
        }

    }

    
    Route::get('/gearman', function() {
        foreach (array(1,2,3) as $row) {
            Queue::push('App\Services\SendMail', array('message' => 'Message' . $row));
        }
    });