既然是结合tp5,咱当然要借鉴tp5的优势
# tp5自定义命令行
这个需要自己看tp5的官方文档,直接搜索就能找到,自己添加command.php文件,我的如下
~~~
/**
* Time: 13:55
*/
return [
'iss\crontab\command\IssServer',
'iss\crontab\command\IssClient',
];
~~~
但是要特别注意,文件的位置,放在目录application/command.php处,或者在入口文件中指定了配置文件目录,则将command.php放在配置目录下的根目录(必须的),因为查看源码如下:

然后再添加个实例类来调用extend扩展中的服务端类,这样写只是为了规范些
~~~
namespace iss\crontab\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class IssServer extends Command {
protected function configure(){
$this->setName('IssServer')->setDescription('定时任务服务端');
}
/**
* 启动服务端服务
* @return \lib\crontab\IssServer
*/
protected function execute(Input $input,Output $output){
$issServer= new \lib\crontab\IssServer();
if($issServer){
$output->writeln('服务端启动成功!');
}else{
$output->writeln('Sorry,服务端启动失败!');
}
}
}
?>
~~~
然后linux中cd到项目根目录,因为我们要用到项目中cli跟入口文件think,所以必须先cd到项目根目录
运行命令
`php think IssServer`
就可以将服务端实例化了,就不必在服务端类里自己new对象了
有些同学可能在安装的时候没有将php变量加入到环境变量中,系统不能识别php命令
可以运行如下命令(/usr/local/php是服务器上php的安装目录)同样可以启动
`/usr/local/php/bin/php -c /usr/local/php/etc/php.ini think IssServer`
这样就可以在扩展中轻松使用tp5的数据库连接等特性
# 设置程序进入后台作为守护进程一直运行

首先是配置server的daemonize属性并加载到服务器启动中,开启守护进程,接着在linux窗口运行启动命令时在命令后加“&”即可,例如
`php think IssServer &`
~~~
class IssServer{
private $serv;
private $debug = true;
public function __construct()
{
$config = config('crontab.server');
//extract($config);
$this->serv = new \swoole_server($config['host'], $config['port']);
$this->serv->set(array(
'daemonize' => $config['daemonize'], //设置程序进入后台作为守护进程运行
'dispatch_mode' => $config['dispatch_mode'], //指定数据包分发策略。1 => 轮循模式,收到会轮循分配给每一个worker进程 2 => 固定模式,根据连接的文件描述符分配worker。这样可以保证同一个连接发来的数据只会被同一个worker处理 3 => 抢占模式,主进程会根据Worker的忙闲状态选择投递,只会投递给处于闲置状态的Worker
'task_worker_num' => $config['task_worker_num'], //服务器开启的task进程数。
'task_ipc_mode' => $config['task_ipc_mode'], //设置task进程与worker进程之间通信的方式。
'log_file' => $config['log_file']
));
$this->serv->on('Start', array($this, 'onStart'));
$this->serv->on('WorkerStart', array($this, 'onWorkerStart'));
$this->serv->on('Connect', array($this, 'onConnect'));
$this->serv->on('Receive', array($this, 'onReceive'));
~~~