一般的定时器是怎么实现的呢?我总结如下:
1.使用Crontab工具,写一个shell脚本,在脚本中调用PHP文件,然后定期执行该脚本;
2.ignore_user_abort()和set_time_limit()配合使用;
3.pcntl_alarm;
4.swoole异步毫秒定时器
Timer做定时器,直接上代码~~
服务端代码(server.php)
serv = new swoole_server('0.0.0.0', 9501);
//初始化swoole服务
$this->serv->set(array(
'worker_num' => 8,
'daemonize' => false, //是否作为守护进程,此配置一般配合log_file使用
'max_request' => 1000,
'log_file' => './swoole.log',
'task_worker_num' => 8
));
//设置监听
$this->serv->on('Start', array($this, 'onStart'));
$this->serv->on('Connect', array($this, 'onConnect'));
$this->serv->on("Receive", array($this, 'onReceive'));
$this->serv->on("Close", array($this, 'onClose'));
$this->serv->on("Task", array($this, 'onTask'));
$this->serv->on("Finish", array($this, 'onFinish'));
//开启
$this->serv->start();
}
public function onStart($serv) {
echo SWOOLE_VERSION . " onStart\n";
}
public function onConnect($serv, $fd) {
echo $fd."Client Connect.\n";
}
public function onReceive($serv, $fd, $from_id, $data) {
echo "Get Message From Client {$fd}:{$data}\n";
// send a task to task worker.
$param = array(
'fd' => $fd
);
// start a task
$serv->task(json_encode($param));
echo "Continue Handle Worker\n";
}
public function onClose($serv, $fd) {
echo "Client Close.\n";
}
public function onTask($serv, $task_id, $from_id, $data) {
echo "This Task {$task_id} from Worker {$from_id}\n";
echo "Data: {$data}\n";
for($i = 0 ; $i < 2 i sleep1 echo task task_id handle i times...\n fd='json_decode($data,' true serv->send($fd['fd'] , "Data in Task {$task_id}");
return "Task {$task_id}'s result";
}
public function onFinish($serv,$task_id, $data) {
echo "Task {$task_id} finish\n";
echo "Result: {$data}\n";
}
}
$server = new server();
客户端代码(client.php)
client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$this->client->on('Connect', array($this, 'onConnect'));
$this->client->on('Receive', array($this, 'onReceive'));
$this->client->on('Close', array($this, 'onClose'));
$this->client->on('Error', array($this, 'onError'));
}
public function connect() {
if(!$fp = $this->client->connect("127.0.0.1", 9501 , 1)) {
echo "Error: {$fp->errMsg}[{$fp->errCode}]\n";
return;
}
}
//connect之后,会调用onConnect方法
public function onConnect($cli) {
fwrite(STDOUT, "Enter Msg:");
swoole_event_add(STDIN,function(){
fwrite(STDOUT, "Enter Msg:");
$msg = trim(fgets(STDIN));
$this->send($msg);
});
}
public function onClose($cli) {
echo "Client close connection\n";
}
public function onError() {
}
public function onReceive($cli, $data) {
echo "Received: ".$data."\n";
}
public function send($data) {
$this->client->send($data);
}
public function isConnected($cli) {
return $this->client->isConnected();
}
}
$client = new Client();
$client->connect();
运行服务端: php server.php
运行客户端: php client.php
结果:
服务端
客户端:
领取方式:点赞关注小编后私信【资料】获取资料领取方式!
部分资料展示:
前60名限时精品福利:
①分布式消息中间件及多进程实战
②Redis缓存击穿/缓存雪崩预防策略
③腾讯高级PHP工程师精品笔试题
④Swoole并发百万的协程使用及分析