【问题标题】:Laravel notify user with results when batched jobs have finished当批处理作业完成时,Laravel 通知用户结果
【发布时间】:2021-09-23 03:46:51
【问题描述】:

我想给潜在的大量客户发送电子邮件,因此我使用批处理并将每封电子邮件作为批处理作业推送,如下所示:

public function __construct(RunReport $runReport, User $run_by) {
        $this->runReport = $runReport;
        $this->run_by = $run_by;
    }

    public function handle()
    {
        $company_detail = CompanyDetail::first();

        $jobs = $this->runReport->runReportReportees
                ->map(fn(RunReportReportee $runReportReportee) => new EmailStatementJob($runReportReportee, $company_detail))
                ->toArray();

        $batch = Bus
            ::batch($jobs)
            ->then(function(Batch $batch) {
                // All completed
                $completed = ($batch->totalJobs - $batch->failedJobs);
                
                $message = "foo";
                $type = "bar";

                $this->run_by->notify(new GenericNotification($message, $type, 'envelope'));
            })
            ->allowFailures()
            ->name('Batch name here trust me')
            ->dispatch();

        return $batch->id;
    }

但是通知行会导致错误Serialization of 'Doctrine\DBAL\Driver\PDOConnection' is not allowed。

如何在批处理完成后通知发起该批处理的用户以及包含的电子邮件发送尝试的结果?或者,我应该如何向几百个客户发送电子邮件并将结果通知用户?

【问题讨论】:

标签: laravel laravel-queue


【解决方案1】:

我最终在帮助下弄明白了——我在 ->then() 回调中使用了 $this,这是我的第一个错误。然后,我没有在作业中通知通知,而是存储了用户 ID 并将其传递给 then() 回调,就像这样

->then(function(Batch $batch) use ($run_by_id) { ... }

在回调中我没有通知用户,而是调用了一个事件

event(new HcpStatementsBatchFinishedEvent($batch, $id));

事件只是存储信息

public function __construct(Batch $batch, int $run_by_sysid)
{
    $this->run_by = User::find($run_by_id);
    $this->batch = $batch;
}

事件的侦听器构建消息并通知用户。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-06
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2016-11-26
    • 2018-12-07
    相关资源
    最近更新 更多