swoole定时器
php备忘
比如说网站上实现一个功能,用户可以保存一个定时任务,比如明天下午5点发一封邮件给我,后天上午10点发一个短信提醒给我,等等。这样的功能用php应该怎么实现呢。
如果没有接触swoole之前,我会把这些定时信息入库,然后用cron去每分钟轮询一次。
缺点有很多,比如说不能精确到秒,也就是说用户设置的时间格式只能精确到分钟,如果设置到秒是无效的。再比如说,用轮询实在是太low了
swoole的定时器很好的解决了这个问题。直接上代码备忘一下。
service
<?php
class Server{
private $serv;
public function __construct() {
$this->serv = new swoole_server("127.0.0.1", 9501);
$this->serv->set(array(
'worker_num' => 1, //一般设置为服务器CPU数的1-4倍
// 'daemonize' => 1, //以守护进程执行
'max_request' => 10000,
'dispatch_mode' => 2,
'task_worker_num' => 8, //task进程的数量
"task_ipc_mode " => 3 , //使用消息队列通信,并设置为争抢模式
//"log_file" => "log/taskqueueu.log" ,//日志
));
$this->serv->on('Receive', array($this, 'onReceive'));
// bind callback
$this->serv->on('Task', array($this, 'onTask'));
$this->serv->on('Finish', array($this, 'onFinish'));
$this->serv->start();
}
public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
//echo "Get Message From Client {$fd}:{$data}n";
// send a task to task worker.
$intt = strtotime($data)-time() ;
$intt = $intt*1000;
if($intt>0){
$serv->after($intt, function() use ($serv, $fd) {
echo "hello world";
});
}
}
public function onTask($serv,$task_id,$from_id, $data) {
return true;
}
public function onFinish($serv,$task_id, $data) {
echo "Task {$task_id} finishn";
//echo "Result: {$data}n";
}
}
$server = new Server();client
<?php
class Client{
private $client;
public function __construct() {
$this->client = new swoole_client(SWOOLE_SOCK_TCP);
}
public function connect() {
if( !$this->client->connect("127.0.0.1", 9501 , 1) ) {
echo "Connect Error";
}
$data = "2016-08-26 09:32:30";
$this->client->send( $data );
}
}
$client = new Client();
$client->connect();