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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles