workerman初始化定时器,workerman重启定时器
介绍
业务中写的定时器,当遇到workerman异常,重启后会失效,所以想项目初始化时启动所有定时器,定时器写在配置文件中,这样业务每次重启时定时器也会随之生效
代码实现如下
/**
*初始化
* @author xingxiong.fei@163.com
* @date 2020-09-03 9:43
*/
public function init($workerId)
{
try {
$log = Container::get('log',[Config::get('','log')]);
$cache = Container::get('cache',[Config::get('','cache')]);
Container::get('session',[Config::get('','session')]);
//数据库初始化
Db::setConfig(Config::get('','database'));
Db::setCache($cache);
Db::setLog($log);
$workerId == 0 && $this->corn();
} catch (\Exception $e) {
Error::exception($e);
}
}
/**定时器
* @author waxiongfeifei@gmail.com
* @date 2020/12/29 下午6:06
*/
public function corn()
{
$filename = __DIR__ . DIRECTORY_SEPARATOR . '../config/corn.php';
if (is_file($filename)) {
include $filename;
}
}
定时器配置文件corn.php
<?php
// +----------------------------------------------------------------------
// | 定时器设置
// +----------------------------------------------------------------------
use Workerman\Lib\Timer;
##定时器1
Timer::add(86400, function(){
$studentClass = new \application\common\model\StudentClass();
$res = $studentClass->countStudentNum();
var_dump($res);
});
##定时器2
Timer::add(86400, function(){
$studentClass = new \application\common\model\StudentClass();
$res = $studentClass->countStudentNum();
});
init在onWorkerStart回调中执行
class Events
{
/**
* 进程启动后初始化数据库连接
*/
public static function onWorkerStart($worker)
{
// 执行应用并响应
Container::get('app')->init($worker->id);
//Redis初始化
global $factory;
$loop = Worker::getEventLoop();
$factory = new Factory($loop);
}