swoole + thinkphp5

使用swoole執行異步定時任務php

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();
相關文章
相關標籤/搜索