TP6 worlerman定時任務


TP6 worlerman

 

 

 

 

 

以下操作我都是在PHP Composer操作

第一步:安裝

composer require topthink/think-worker

項目根目錄config文件夾增加

worker.php

worker_server.php

第二步:修改相關配置

修改worker_server.php文件:

‘worker_class’ = ‘app\admin\controller\Dingshi’;

這里的路徑要全我這里項目配置了多應用模式,默認的tp6是單應用模式,具體查看tp6官方文檔

 

 

 

第三步:Dingshi.php代碼

<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\Request;

use Workerman\Lib\Timer;

use think\worker\Server;

class Dingshi extends Server

{

protected $socket = 'websocket://0.0.0.0:2346';

public function __construct()

{

parent::__construct();

$this->onMessage();

// 或者這樣調用

$this->worker->onWorkerStart = function($worker)

{

echo "Worker starting...\n";

Timer::add(10, array($this, 'index'), array(), true);

};

}

/**

* 收到信息

* @param $connection

* @param $data

*/

public function onMessage()

{

$this->worker->onMessage = function($connection, $data)

{

$connection->send($data."123");

};

}

/**

* 顯示資源列表

*

* @return \think\Response

*/

public function index()

{

file_put_contents('a.log',date('Y-m-d H:i:s',time()).'執行了一次定時任務。'.PHP_EOL,FILE_APPEND);

}

}

第四步:開啟workerman服務

php think worker:server

運行效果如下:

Worker starting... 這個就是Dingshi.php 21行數據

關閉服務是ctrl+C 使用過程中不要關閉或者退出

 

 

 

第五步:測試通信

打開網頁:http://localhost:2346

運行效果如下:

 

 

 

我用的是谷歌 F12在console里面輸入

ws = new WebSocket("ws://127.0.0.1:2346");

ws.onopen = function() {

ws.send('admin');

};

ws.onmessage = function(e) {

alert("收到服務端的消息:" + e.data);

};

 

 

 

這個時候頁面會彈出 'admin123' 這個時候說明通信成功了,admin123在Dingshi.php 34行

第六步:查看定時任務效果

Dingshi.php 22行

Timer::add(10, array($this, 'index'), array(), true);

這里每10秒會執行下面的index方法

file_put_contents('a.log',date('Y-m-d H:i:s',time()).'執行了一次定時任務。'.PHP_EOL,FILE_APPEND);

這個是在網頁根目錄a.log文件寫數據效果如下

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM