使用dispatchNow检测作业是否已被调度 [英] Detecting if a job has been dispatched using dispatchNow

查看:93
本文介绍了使用dispatchNow检测作业是否已被调度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一份工作,在某些情况下会调用另一份工作

I have a job that under certain circumstances calls another job

<?php namespace App\Jobs;

use App\Models\Account;

class EnqueueScheduledDownloads implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $account;

    public function __construct(Account $account)
    {
        $this->account = $account;
    }

    public function handle()
    {
        foreach($this->account->pending_downloads as $file)
        {
            DownloadFile::dispatch($file);
        }
    }
}

虽然下载作业通常在队列中执行;有时候,例如在测试过程中,如果整个链以阻塞的方式同步处理,将会使我的生活变得更加轻松.我希望能够执行以下操作:

While the download job is usually executed in a queue; there are times, for example during testing, where it would make my life much easier if the whole chain was processed synchronously in a blocking fashion. I would like to be able to do something like this:

public function handle()
{
    foreach($this->account->pending_downloads as $file)
    {
        if($this->getDispatchMode() == 'sync') {
            DownloadFile::dispatchNow($file);
        } else {
            DownloadFile::dispatch($file);
        }

    }
}

这可能吗?

推荐答案

经过一番摸索,我能够回答自己的问题.对的,这是可能的;如果通过dispatchNow()调度作业,则Queueable对象的job属性将为null,而如果使用dispatch()在连接上调度该作业,则将其设置为Illuminate \ Contracts \ Queue \ Job的实现.这样可以更改handle方法:

After a bit of poking around I was able to answer my own question. Yes it is possible; if a job is dispatched via dispatchNow() the job property of the Queueable object will be null, whereas if it is dispatched on a connection using dispatch() it will be set to an implementation of Illuminate\Contracts\Queue\Job. So the handle method can be changed as such:

public function handle()
{
    foreach($this->account->pending_downloads as $file)
    {
        if(is_null($this->job)) {
            DownloadFile::dispatchNow($file);
        } else {
            DownloadFile::dispatch($file);
        }
    }
}

它将按预期工作.我可以通过创建新工作来找到此解决方案:

And it will work as expected. I was able to find this solution by creating a new job:

<?php namespace App\Jobs;

class TestJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct()
    {
    }

    public function handle()
    {
        dump(get_object_vars($this));
    }
}

并将其分派到各种队列和连接以及dispatchNow()并观察输出.此外,还可以恢复连接并排队从$this->job派发作业的队列:

and dispatching it on various queue and connections as well as with dispatchNow() and observing the output. Furthermore it is possible to retreive the connection and queue the job was dispatched on from the $this->job:

public function handle()
{
    echo $this->job->getConnectionName();
    echo $this->job->getQueue();
}

这篇关于使用dispatchNow检测作业是否已被调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆