安装
#在项目根目录执行以下指令
# 如果是tp5.0使用1.0的版本(使用1.0任务会执行4次)
# composer require topthink/think-worker=1.0.*
composer require topthink/think-worker
在项目根目录创建服务启动文件 server.php
<?php
define('APP_PATH', __DIR__ . '/application/');
define("BIND_MODULE", "server/Worker");
// 加载框架引导文件
require __DIR__ . '/thinkphp/start.php';
在application里创建server模块,并在server里创建控制器 Worker.php
<?php
namespace app\server\controller;
use think\worker\Server;
class Worker extends Server
{
public function onWorkerStart($work)
{
$handle=new Collection();
$handle->add_timer();
}
}
在application里创建server模块,并在server里创建控制器 Collection.php
<?php
namespace app\server\controller;
use think\Controller;
use Workerman\Lib\Timer;
class Collection extends Controller
{
public function __construct()
{
parent::__construct();
}
public function add_timer()
{
Timer::add(10, array($this, 'index'), array(), true); //时间间隔过小,运行会崩溃
}
public function index()
{
return json(['msg' => "此次采集数据共 10 条。", 'total' => 10]);
}
}
启动服务 php server.php start