The use of a timer is provided in swoole
$server->tick(1000, function() use ($server, $fd) { $server->send($fd, "hello world"); });
I used it in the beginning. Look at the code
<?php $serv = new Swoole\Server("0.0.0.0", 9501); $serv->set(array( 'worker_num' => 1, //worker process num )); $serv->on('connect', function ($serv, $fd){ echo "Client ".$fd."Successful connection \n"; }); $serv->on('receive', function ($serv, $fd, $reactor_id, $data) { echo "Client ".$fd."Message:".$data."\n"; $serv->send($fd, 'Swoole The message you sent has been introduced: '.$data); }); $serv->on('close', function ($serv, $fd) { echo "Client {$fd}Close connection\n"; }); $serv->on('WorkerStart', function ($serv, $worker_id){ $serv->tick(2000, function(){ echo "Perform timer task ".time()." \n"; }); }); $serv->start();
When I started to use the timer, I put it into onWorkStart to execute. In this way, I can ensure that the timer can run normally in the case of a single worker process. But for swoole, it obviously insults its "talent" by making it work in a single process. So I set work num to 2 and then an accident happened, as shown in the figure below
We can see that there are two schedulers that perform the same task twice, so this method is not right. Of course, we can avoid this situation by judging the worker ﹐ ID in onWorkStart, but later I found that there is another relatively better way, which is to use the user-defined process
bool Server->addProcess(Process $process);
The code is as follows:
<?php $serv = new Swoole\Server("0.0.0.0", 9501); $serv->set(array( 'worker_num' => 2, //worker process num )); //Create custom process $process = new Swoole\Process(function($process) use ($serv) { $serv->tick(2000, function(){ echo "Perform timer task ".time()." \n"; }); }); $serv->addProcess($process); $serv->on('connect', function ($serv, $fd){ echo "Client ".$fd."Successful connection \n"; }); $serv->on('receive', function ($serv, $fd, $reactor_id, $data) { echo "Client ".$fd."Message:".$data."\n"; $serv->send($fd, 'Swoole The message you sent has been introduced: '.$data); }); $serv->on('close', function ($serv, $fd) { echo "Client {$fd}Close connection\n"; }); $serv->start();
Execution effect:
ok! Perfect execution