在GatewayWorker的onWorkerStart方法中,調(diào)用了Crontab模塊。
gateway進(jìn)程數(shù)設(shè)置為4,經(jīng)過測試,發(fā)現(xiàn)每次執(zhí)行都會(huì)出現(xiàn)4個(gè)結(jié)果。
有什么辦法能讓Crontab模塊只執(zhí)行1次,而不是執(zhí)行多次呢?
使用$pid = posix_getpid()
方法,獲取到的是5位數(shù)的id,數(shù)字是隨機(jī)的,并不固定。
有什么辦法能獲得$pid映射的$worker_id,結(jié)果如0、1、2、3這樣的呢?
//GatewayWorker/Applications/YourApp/Events.php
use Workerman\Crontab\Crontab;
public static function onWorkerStart($businessWorker)
{
// 每分鐘的第1秒執(zhí)行.
self::$crontab = new Crontab('1 * * * * *', function () {
// echo date('Y-m-d H:i:s') . "\n";
echo posix_getpid() . "\n";
});
}
輸出內(nèi)容:
13080
13091
13093
13094
還有一個(gè)問題,就是打印$businessWorker
這個(gè)參數(shù),輸出的是null。這個(gè)是什么原因呢?
測試了一下,設(shè)置$worker->count = 1;
就可以實(shí)現(xiàn)Crontab模塊只執(zhí)行1次。
不知道還有沒有其他更好的辦法?
通過查詢開發(fā)手冊(cè)和論壇搜索,目前已找到另外兩種辦法。
1、在start_gateway.php所在目錄里建立一個(gè)start_worker.php,內(nèi)容類似
<?php
use Workerman\Worker;
use Workerman\Timer;
require_once __DIR__ . '/../../vendor/autoload.php';
$worker = new Worker("http://0.0.0.0:1258");
// 回調(diào)函數(shù)
$worker->onWorkerStart = function ($worker) {
Timer::add(3, function () {
echo posix_getpid() . "——" . date('Y-m-d H:i:s') . "\n";
});
};
if (!defined('GLOBAL_START')) {
Worker::runAll();
}
以上內(nèi)容來自http://wtbis.cn/q/8853
2、添加一個(gè)回調(diào)函數(shù):
//GatewayWorker/Applications/YourApp/start_businessworker.php
use \Workerman\Timer;
$worker->onWorkerStart = function ($worker) {
// 只在id編號(hào)為0的進(jìn)程上設(shè)置定時(shí)器,其它1、2、3號(hào)進(jìn)程不設(shè)置定時(shí)器
if ($worker->id === 0) {
Timer::add(3, function () {
echo "4個(gè)worker進(jìn)程,只在0號(hào)進(jìn)程設(shè)置定時(shí)器\n";
});
} else {
echo "worker->id={$worker->id}\n";
}
};
也可以這樣Event.php里
calss Event
{
public static function onWorkerStart($worker)
{
if($worker->id = 0) {
}
}
}
這樣會(huì)報(bào)錯(cuò)的。
Deprecated: call_user_func() expects parameter 1 to be a valid callback, non-static method Events::onWorkerStart() should not be called statically in /www/wwwroot/api.xxx.cn/GatewayWorker/vendor/workerman/gateway-worker/src/BusinessWorker.php on line 214
對(duì)啊,我是這樣實(shí)現(xiàn)的。文件路徑是“GatewayWorker/Applications/YourApp/Events.php”,在Events類下,public static function onWorkerStart($businessWorker),無法打印$businessWorker
直接復(fù)制您上面的代碼,放在Events類里。啟動(dòng)服務(wù)后,會(huì)拼命地打印“ Gateway: Worker->name conflict. Key:127.0.0.1:YourAppBusinessWorker:0”