Laravel-按顺序运行作业 [英] Laravel - Running Jobs in Sequence

查看:162
本文介绍了Laravel-按顺序运行作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Laravel,他正在一个运行Horizo​​n的项目中学习工作.我被困在一个地方,需要一次又一次地做几次相同的工作.

I am learning Laravel, working on a project which runs Horizon to learn about jobs. I am stuck at one place where I need to run the same job a few times one after one.

这是我目前正在做的事情

Here is what I am currently doing

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Subscriptions;
class MailController extends Controller
{


    public function sendEmail() {
        Subscriptions::all()
        ->each(function($subscription) {
            SendMailJob::dispatch($subscription);
        });
    }
}

这很好用,除了它可以跨多个工人运行作业,而且顺序不保证.有什么方法可以依次运行作业吗?

This works fine, except it runs the job's across several workers and not in a guaranteed order. Is there any way to run the jobs one after another?

推荐答案

您正在寻找的是工作链.

What you are looking for, as you mention in your question, is job chaining.

来自Laravel文档

作业链接使您可以指定应按顺序运行的排队作业列表.如果序列中的一个作业失败,则其余的作业将不会运行.要执行排队的作业链,可以对任何可调度作业使用withChain方法:

Job chaining allows you to specify a list of queued jobs that should be run in sequence. If one job in the sequence fails, the rest of the jobs will not be run. To execute a queued job chain, you may use the withChain method on any of your dispatchable jobs:

ProcessPodcast::withChain([
    new OptimizePodcast,
    new ReleasePodcast
])->dispatch();

所以在上面的示例中

$mailJobs = Subscriptions::all()
    ->map(function($subscription) {
        return new SendMailJob($subscription);
    });

Job::withChain($mailJobs)->dispatch()

应该给出预期的结果!

更新

如果您不想使用初始作业进行链接(如上面的文档示例中所示),则应该能够创建一个具有use Dispatchable;的空Job类.那你可以用我上面的例子

If you do not want to use an initial job to chain from (like shown in the documentation example above) you should be able to make an empty Job class that that has use Dispatchable;. Then you can use my example above

这篇关于Laravel-按顺序运行作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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