1、首先通过 composer 安装workerman,在thinkphp5完全开发手册的扩展-》coposer包-》workerman有详细说明:
#在项目根目录执行以下指令
composer require topthink/think-worker
2.在项目根目录创建服务启动文件 server.php:
<?php define('APP_PATH', __DIR__ . '/application/'); define("BIND_MODULE", "server/Worker"); // 加载框架引导文件 require __DIR__ . '/thinkphp/start.php';
3、在application里创建server模块,并在server里创建控制器 Worker.php:
<?php namespace app\server\controller; use think\worker\Server; class Worker extends Server { protected $processes=1; public function onWorkerStart($work) { $handle=new Index(); $handle->add_timer(); } }
4.创建Index.php类.定义一个每秒钟执行一次的定时器,在定时器里增加条件判断,当当前时间等于要执行的时间时,就执行此任务
<?php namespace app\server\controller; use Workerman\Lib\Timer; class Index { public function add_timer(){ Timer::add(1, array($this, 'index'), array(), true); } public function index(){ //每天0点执行任务 if(time()/86400===0){ echo date("Y-m-d H:i:s"); } //每天8点执行任务 if(time()/86400===28800){ echo date("Y-m-d H:i:s"); } }
由于workerman把php文件从磁盘读取解析一次后便会常驻内存,对于一些相隔很久才执行一次的任务,我们可以在定时器中再调用一个只执行一次的定时器来执行这些任务
<?php namespace app\server\controller; use Workerman\Lib\Timer; class Index { public function add_timer(){ Timer::add(1, array($this, 'index'), array(), true); } public function index(){ //每过24小时执行一次 if(time()%86400===0){ Timer::add(5, array($this, 'test'), array(), false); } } function testt(){ echo 1; } }
5、启动服务 php server.php start -d