swoole + thinkphp5

本文介绍如何使用Swoole在ThinkPHP框架中实现异步定时任务。通过配置Swoole服务器参数并定义定时任务回调函数,可以有效提高系统的响应速度及资源利用率。

使用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();

转载于:https://my.oschina.net/u/2544857/blog/616830

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值