Yii2 队列 shmilyzxt/yii2-queue 简单概述
shmilyzxt/yii2-queue 简单解释:1.我用的yii2高级版,我们从配置开始看代码,这里我用的是mysql队列,首先配置文件,我把queue配置项写在根目录 2个sql文件到数据库中建立队列数据表和执行任务失败时的数据表. 2.推送任务开始语法: canPush()) {
//beforePush 入队列前的事件
$this->trigger(self::EVENT_BEFORE_PUSH);
//入队列
$ret = $this->push($job,$data,$queue);
//afterPush 入队列后的事件
$this->trigger(self::EVENT_AFTER_PUSH);
return $ret;
} else {
throw new Exception("max jobs number exceed! the max jobs number is {$this->maxJob}");
}
}
注释:这里最好去看看yii2 event事件类,http://www.digpage.com/event.html 关于入队列: 3.后台运行命令处理队列,例: 启动命令后,我们来看代码:首先执行: pop($queueName);
}catch (Exception $e){
throw $e;
continue;
}
if($job instanceof Job){
//判断执行错误的次数是否大于传入的执行次数
if($attempt > 0 && $job->getAttempts() > $attempt){
$job->failed();
}else{
try{
//throw new Exception("test failed");
$job->execute();
}catch (Exception $e){
//执行失败,判断是否被删除,重新入队
if (! $job->isDeleted()) {
$job->release($delay);
}
}
}
}else{
self::sleep($sleep);
}
if (self::memoryExceeded($memory)) {
self::stop();
}
}
}
注释:在 getQueue($queue);
if (!is_null($this->expire)) {
//$this->releaseJobsThatHaveBeenReservedTooLong($queue);
}
$tran = $this->connector->beginTransaction();
//判断是否有一个可用的任务需要执行
if ($job = $this->getNextAvailableJob($queue)) {
$this->markJobAsReserved($job->id);
$tran->commit();
$config = array_merge($this->jobEvent,[
'class' => 'shmilyzxtqueuejobsDatabaseJob','queue' => $queue,'job' => $job,'queueInstance' => $this,]);
return Yii::createObject($config);
}
$tran->commit();
return false;
}
至于: trigger(self::EVENT_BEFORE_EXECUTE,new JobEvent(["job" => $this,'payload' => $this->getPayload()]));//beforeExecute 执行任务之前的一个事件 在JobEvent中并没有什么可执行的代码
$this->resolveAndFire();//真正执行的任务的方法
}
/**
* 真正任务执行方法(调用hander的handle方法)
* @param array $payload
* @return void
*/
protected function resolveAndFire()
{
$payload = $this->getPayload();
$payload = unserialize($payload); //反序列化数据
$type = $payload['type'];
$class = $payload['job'];
if ($type == 'closure' && ($closure = (new Serializer())->unserialize($class[1])) instanceof Closure) {
$this->handler = $this->getHander($class[0]);
$this->handler->closure = $closure;
$this->handler->handle($this,$payload['data']);
} else if ($type == 'classMethod') {
$payload['job'][0]->$payload['job'][1]($this,$payload['data']);
} else if ($type == 'staticMethod') {
$payload['job'][0]::$payload['job'][1]($this,$payload['data']);
} else {//执行的`SendMail`类的`handle($job,$data)`方法
$this->handler = $this->getHander($class);
$this->handler->handle($this,$payload['data']);
}
//执行完任务后删除
if (!$this->isDeletedOrReleased()) {
$this->delete();
}
}
最后到了执行的 getAttempts() > 3){
$this->failed($job);
}
$payload = $job->getPayload();
echo '
';print_r($payload); //$payload即任务的数据,你拿到任务数据后就可以执行发邮件了 //TODO 发邮件 } 总结以上所述是小编给大家介绍的Yii2 队列 shmilyzxt/yii2-queue简介,希望对大家有所帮助。程序员遇到问题都会上(编程之家52php.cn)查找问题解答方法!如果觉得站点还不错,随手转发给程序员朋友一下! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |