Table of Contents
1、简介
2、定义调度
3、任务输出
4、任务钩子
Home Backend Development PHP Tutorial [ Laravel 5.2 文档 ] 服务 -- 任务调度

[ Laravel 5.2 文档 ] 服务 -- 任务调度

Jun 23, 2016 pm 01:17 PM

1、简介

在以前,开发者需要为每一个需要调度的任务编写一个Cron条目,这是很让人头疼的事。你的任务调度不在源码控制中,你必须使用SSH登录到服务器然后添加这些Cron条目。Laravel命令调度器允许你平滑而又富有表现力地在Laravel中定义命令调度,并且服务器上只需要一个Cron条目即可。

任务调度定义在 app/Console/Kernel.php文件的 schedule方法中,该方法中已经包含了一个示例。你可以自由地添加你需要的调度任务到 Schedule对象。

开启调度

下面是你唯一需要添加到服务器的Cron条目:

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1
Copy after login

该Cron将会每分钟调用Laravel命令调度,然后,Laravel评估你的调度任务并运行到期的任务。

2、定义调度

你可以在 App\Console\Kernel类的 schedule方法中定义所有调度任务。开始之前,让我们看一个调度任务的例子,在这个例子中,我们将会在每天午夜调度一个被调用的闭包。在这个闭包中我们将会执行一个数据库查询来清空表:

<?phpnamespace App\Console;use DB;use Illuminate\Console\Scheduling\Schedule;use Illuminate\Foundation\Console\Kernel as ConsoleKernel;class Kernel extends ConsoleKernel{    /**     * 应用提供的Artisan命令     *     * @var array     */    protected $commands = [        'App\Console\Commands\Inspire',    ];    /**     * 定义应用的命令调度     *     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule     * @return void     */    protected function schedule(Schedule $schedule)    {        $schedule->call(function () {            DB::table('recent_users')->delete();        })->daily();    }}
Copy after login

除了调度闭包调用外,还可以调度Artisan命令和操作系统命令。例如,可以使用 command方法来调度一个Artisan命令:

$schedule->command('emails:send --force')->daily();
Copy after login

exec命令可用于发送命令到操作系统:

$schedule->exec('node /home/forge/script.js')->daily();
Copy after login

2.1 调度常用选项

当然,你可以分配多种调度到任务:

方法 描述
->cron('* * * * *'); 在自定义Cron调度上运行任务
->everyMinute(); 每分钟运行一次任务
->everyFiveMinutes(); 每五分钟运行一次任务
->everyTenMinutes(); 每十分钟运行一次任务
->everyThirtyMinutes(); 每三十分钟运行一次任务
->hourly(); 每小时运行一次任务
->daily(); 每天凌晨零点运行任务
->dailyAt('13:00'); 每天13:00运行任务
->twiceDaily(1, 13); 每天1:00 & 13:00运行任务
->weekly(); 每周运行一次任务
->monthly(); 每月运行一次任务
->quarterly(); 每个季度运行一次
->yearly(); 每年运行一次

这些方法可以和额外的约束一起联合起来创建一周特定时间运行的更加细粒度的调度,例如,要每周一调度一个命令:

$schedule->call(function () {    // 每周星期一13:00运行一次...})->weekly()->mondays()->at('13:00');
Copy after login

下面是额外的调度约束列表:

方法 描述
->weekdays(); 只在工作日运行任务
->sundays(); 每个星期天运行任务
->mondays(); 每个星期一运行任务
->tuesdays(); 每个星期二运行任务
->wednesdays(); 每个星期三运行任务
->thursdays(); 每个星期四运行任务
->fridays(); 每个星期五运行任务
->saturdays(); 每个星期六运行任务
->when(Closure); 基于特定测试运行任务

基于测试的约束条件

when方法用于限制任务在通过给定测试之后运行。换句话说,如果给定闭包返回 true,只要没有其它约束条件阻止任务运行,该任务就会执行:

$schedule->command('emails:send')->daily()->when(function () {    return true;});
Copy after login

reject方法和when相反,如果reject方法返回true,调度任务将不会执行:

$schedule->command('emails:send')->daily()->reject(function () {    return true;});
Copy after login

使用when方法链的时候,调度命令将只会执行返回true的when方法。

2.2 避免任务重叠

默认情况下,即使前一个任务仍然在运行调度任务也会运行,要避免这样的情况,可使用 withoutOverlapping方法:

$schedule->command('emails:send')->withoutOverlapping();
Copy after login

在本例中,Artisan命令 emails:send每分钟都会运行,如果该命令没有在运行的话。如果你的任务在执行时经常大幅度的变化,那么 withoutOverlapping方法就非常有用,你不必再去预测给定任务到底要消耗多长时间。

3、任务输出

Laravel调度器为处理调度任务输出提供了多个方便的方法。首先,使用 sendOutputTo方法,你可以发送输出到文件以便稍后检查:

$schedule->command('emails:send')         ->daily()         ->sendOutputTo($filePath);
Copy after login

如果你想要追加输出到给定文件,可以使用appendOutputTo方法:

$schedule->command('emails:send')         ->daily()         ->appendOutputTo($filePath);
Copy after login

使用 emailOutputTo方法,你可以将输出发送到电子邮件,注意输出必须首先通过 sendOutputTo方法发送到文件。还有,使用电子邮件发送任务输出之前,应该配置Laravel的电子邮件服务:

$schedule->command('foo')         ->daily()         ->sendOutputTo($filePath)         ->emailOutputTo('foo@example.com');
Copy after login

注意: emailOutputTo和 sendOutputTo方法只对 command方法有效,不支持 call方法。

4、任务钩子

使用 before和 after方法,你可以指定在调度任务完成之前和之后要执行的代码:

$schedule->command('emails:send')         ->daily()         ->before(function () {             // Task is about to start...         })         ->after(function () {             // Task is complete...         });
Copy after login

ping URL

使用 pingBefore和 thenPing方法,调度器可以在任务完成之前和之后自动ping给定的URL。该方法在通知外部服务时很有用,例如 Laravel Envoyer,在调度任务开始或完成的时候:

$schedule->command('emails:send')         ->daily()         ->pingBefore($url)         ->thenPing($url);
Copy after login

使用 pingBefore($url)或 thenPing($url)特性需要安装HTTP库Guzzle,可以在 composer.json文件中添加如下行来安装Guzzle到项目:

"guzzlehttp/guzzle": "~5.3|~6.0"
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles