adiafora/laravel-cron-schedule

使用不同的cron运行Laravel任务调度器的功能

1.6.5 2022-04-28 09:43 UTC

This package is auto-updated.

Last update: 2024-09-28 14:58:12 UTC


README

Laravel任务调度 是管理cron的一种很好的方式。但是,文档中包含以下警告

默认情况下,同时安排的多个任务将根据它们在调度方法中定义的顺序依次执行。如果您有长时间运行的任务,这可能会导致后续任务开始的时间远晚于预期。

可以使用 runInBackground() 方法来帮助您。但是!

runInBackground 方法只能在通过命令和exec方法调度任务时使用。

如果我使用代码而不是运行命令,我该怎么办?..

使用我们的包,您可以在服务器上运行尽可能多的cron,并为每个cron指定其名称。在 App\Console\Kernel 中,您可以在 onCron() 方法中指定哪个cron应该处理此任务。未指定名称的cron将被视为默认cron。您不需要为此cron指定任何内容即可将其任务放入此cron。

安装

运行

    composer require adiafora/laravel-cron-schedule

用法

App\Console\Kernel

App\Console\Kernel 中,将以下行替换为

    use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

    use Adiafora\Schedule\Kernel as ConsoleKernel;

服务器

现在删除服务器上的cron条目

 * * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

然后添加一个条目代替

 * * * * * cd /path-to-your-project && php artisan cron-schedule:run >> /dev/null 2>&1

您的调度器现在像以前一样正常工作。

另一个cron

您可以通过使用选项 --cron= 来指定名称的方式,向您的服务器添加另一个cron。让我们给它起一个名字 longTime

 * * * * * cd /path-to-your-project && php artisan cron-schedule:run --cron=longTime >> /dev/null 2>&1

现在您可以为此调度器中的任何任务指定此cron的名称。

    $schedule->call(function () {
        $this->mailService->send();
        sleep(60);
        $this->mailService->send(true);
    })
        ->onCron('longTime')
        ->dailyAt('03:00');

    $schedule->call(function () {
        $this->report->prepare();
    })
        ->dailyAt('03:00');

请注意,准备报告的任务将正好在03:00执行,而不会等待发送电子邮件!这样,您可以创建尽可能多的cron,为它们命名,并将任务分配给它们,按照您的喜好分配。在每个cron中,任务将严格按照指定的时间启动,而不会等待其他在相同时间在其他cron中启动的任务。

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。