编程

Laravel 调度器(Scheduler) 中的五个函数

164 2024-10-05 13:42:00

本文是关于 Laravel Scheduler 的一些函数介绍,它用于运行计划任务(也称为 cron 作业)。

让我们来探索一些鲜为人知的调度器函数:

1. skip() & when()

如果你希望调度任务仅在某些条件为 true 时执行,请使用 when() 内联设置这些条件:

$schedule->command('your:command')->when(function () {
    return some_condition();
});

skip()when() 方法的反面。如果 skip 方法内返回的是 true,则调度任务不会执行:

$schedule->command('emails:send')->daily()->skip(function(){
    return Calendar::isHolidauy();
});

2. withoutOverlapping()

你可能正在运行一个关键任务,该任务一次只能运行一个实例。withoutOverlapping() 确保调度的任务不会重叠调用,从而防止潜在的冲突。

$schedule->command('your:command')->withoutOverlapping();

3. thenPing()

执行完任务后,你可能希望 ping 一个网址,用来通知其他服务或者触发其他操作。thenPing() 让你实现无缝操作。

$schedule->command('your:command')->thenPing('http://example.com/webhook');

4. runInBackground()

如果你希望调度的任务在后台运行而不至于耽搁其他进程,则可以调用 runInBackground()

$schedule->command('your:command')->runInBackground();

5. evenInMaintenanceMode()

$schedule->command('your:command')->evenInMaintenanceMode();

试试看;在任务自动化中使用这些调度器函数,使代码更容易。