一、首先经过 composer 安装workerman,在thinkphp5彻底开发手册的扩展-》coposer包-》workerman有详细说明:php
#在项目根目录执行如下指令
composer require topthink/think-worker
2.在项目根目录建立服务启动文件 server.php:thinkphp
<?php define('APP_PATH', __DIR__ . '/application/'); define("BIND_MODULE", "server/Worker"); // 加载框架引导文件 require __DIR__ . '/thinkphp/start.php';
三、在application里建立server模块,并在server里建立控制器 Worker.php:app
<?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类.定义一个每秒钟执行一次的定时器,在定时器里增长条件判断,当当前时间等于要执行的时间时,就执行此任务composer
<?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"); } }
五、启动服务 php server.php start -d框架