使用swoole执行异步定时任务
define('APP_PATH', __DIR__ . '/../application/');
define('APP_DEBUG', true);
require_once __DIR__ . '/../../thinkphp5/start.php';
class swoole{
protected $serv;
protected $application;
function __construct() {
$this->serv = new \swoole_server("127.0.0.1", 9501);
$this->serv->set([
'daemonize' => 0, //守护进程化。设置daemonize => 1时,程序将转入后台作为守护进程运行
'worker_num' => 1, //设置启动的worker进程数。业务代码是全异步非阻塞的,这里设置为CPU的1-4倍最合理
'task_worker_num' => 10
]);
$this->serv->on('WorkerStart', [$this, 'onWorkerStart']);
$this->serv->on('receive', function($serv, $fd, $from_id, $data) {});
$this->serv->on('task', [$this, 'onTask']);
$this->serv->on('finish', function($serv, $task_id, $data) {
echo "AsyncTask[$task_id] Finish: $data" . PHP_EOL;
});
$this->serv->start();
}
public function onWorkerStart(\swoole_server $serv, $worker_id) {
if($worker_id == 0) {
echo "init.\n";
$serv->tick(500, [$this, 'taskfun']);
}
}
public function onTask($serv, $task_id, $from_id, $data) {
try {
$dispatch = [
'type' => 'module',
'module' => ['api','index','info'],
];
\think\App::dispatch($dispatch);
\think\App::run();
} catch (\Exception $e) {
var_dump($e);
}
return "$data -> IS OK";
}
public function taskfun(){
$this->serv->task(time());
}
}
new swoole();