最近项目中需要用到毫秒级定时器,但是服务器中的crontab定时任务最小是分钟,所以使用了swoole的定时器。
需要先安装php swoole 扩展
<?php
/**
* Created by PhpStorm.
* User: 江雪
* Date: 2019/4/29 0029
* Time: 21:19
*/
namespace app\web\controller;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
class Times extends Command
{
protected function configure()
{
$this->setName('ds')
->setDescription('times');
}
protected function execute(Input $input, Output $output)
{
$serv = new \swoole_server("0.0.0.0",9505);
$serv->on("WorkerStart",function ($serv,$woker_id){
if ($woker_id == 0){
//每隔1000ms触发一次
swoole_timer_tick(1000, function ($timer_id) {
// echo "hello\n";
});
}
});
$serv->on("receive",function ($serv,$fd,$from_id,$data){
$serv->send($fd,"Server:".$data);
});
$serv->start();
}
}
1.配置command.php文件,位于application/command.php
configure函数是在命令行中用list命令列出所有任务的时候回显示的出的提示,execute函数是说要执行的命令,在这里可以直接调用其他函数,完成例如统计等任务工作,然后用output输出到命令行
打开命令行,运行php think test命令test命令execute方法中运行的方法就会运行