[Laravel 5.1 Document] Service--Task scheduling

Source: Internet
Author: User

1. Introduction

In the past, developers need to write a cron entry for every task that needs to be scheduled, which is a very frustrating thing to do. Your task Scheduler is not in source control, you must use SSH to log on to the server and add these cron entries. The Laravel command Scheduler allows you to define command scheduling in Laravel in a smooth and expressive manner, and only one cron entry is required on the server.

Task scheduling is defined in the app/Console/Kernel.php file's schedule method, and the method already contains an example. You are free to add the dispatch task you need to the Schedule object.

1.1 Turn on scheduling

Here's the only cron entry you'll need to add to the server:

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

The cron will call the Laravel command schedule every minute, and then laravel evaluate your dispatch task and run the task that expires.

2. Define Scheduling

You can App\Console\Kernel schedule define all scheduling tasks in the methods of the class. Before we begin, let's look at an example of a dispatch task, in which we will dispatch a called closure at midnight every day. In this closure we will execute a database query to clear the table:

<?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();    }}

In addition to dispatching closure calls, you can also dispatch artisan commands and operating system commands. For example, you can use command a method to schedule a artisan command:

$schedule->command(‘emails:send --force‘)->daily();

execCommands can be used to send commands to the operating system:

$schedule->exec(‘node /home/forge/script.js‘)->daily();
2.1 Scheduling common options

Of course, you can assign multiple dispatches to tasks:

Method Description
->cron(‘* * * * *‘); To run a task on a custom cron schedule
->everyMinute(); Run a task every minute
->everyFiveMinutes(); Run a task every five minutes
->everyTenMinutes(); Run a task every 10 minutes
->everyThirtyMinutes(); Run a task every 30 minutes
->hourly(); Run a task once per hour
->daily(); Run a task 0 o'clock in the morning every day
->dailyAt(‘13:00‘); Run a task 13:00 every day
->twiceDaily(1, 13); Run a task every day AT & 13:00
->weekly(); Run a task once a week
->monthly(); Run a task once a month

These methods can be combined with additional constraints to create finer-grained schedules that run at a specific time of the week, for example, to schedule one command per week:

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

The following is an additional list of schedule constraints:

Method Description
->weekdays(); Run tasks only on weekdays
->sundays(); Run a task every Sunday
->mondays(); Run a task every week
->tuesdays(); Run tasks every Tuesday
->wednesdays(); Run tasks every Wednesday
->thursdays(); Run tasks every Thursday
->fridays(); Run tasks every Friday
->saturdays(); Run tasks every Saturday
->when(Closure); Run a task based on a specific test
2.1.1 Test-based constraint conditions

whenmethod to restrict a task from running after a given test. In other words, if a given closure is returned true , the task executes as long as no other constraints prevent the task from running:

$schedule->command(‘emails:send‘)->daily()->when(function () {    return true;});
2.2 Avoiding overlapping tasks

By default, even if the previous task is still running the dispatch task, to avoid this situation, you can use the withoutOverlapping method:

$schedule->command(‘emails:send‘)->withoutOverlapping();

In this example, the artisan command emails:send runs every minute, if the command is not running. If your task often changes drastically during execution, then the method is withoutOverlapping very useful and you don't have to predict how long a given task will take.

3. Task Output

The Laravel Scheduler provides several convenient methods for processing scheduling task output. First, using sendOutputTo the method, you can send output to a file for later inspection:

$schedule->command(‘emails:send‘)         ->daily()         ->sendOutputTo($filePath);

Using emailOutputTo the method, you can send the output to an e-mail message, noting that the output must first be sendOutputTo sent to a file by method. Also, before sending the task output using e-mail, you should configure the Laravel e-mail Service:

$schedule->command(‘foo‘)         ->daily()         ->sendOutputTo($filePath)         ->emailOutputTo(‘[email protected]‘);

Note: The emailOutputTo and sendOutputTo methods command are only valid for methods and do not support call methods.

4. Task Hooks

Using the before and after methods, you can specify the code to execute before and after the dispatch task is completed:

$schedule->command(‘emails:send‘)         ->daily()         ->before(function () {             // Task is about to start...         })         ->after(function () {             // Task is complete...         });
4.1 Ping URL

Using pingBefore and thenPing methods, the scheduler can automatically ping a given URL before and after the task is completed. This method is useful when notifying an external service, such as Laravel Envoyer, when a scheduled task starts or finishes:

$schedule->command(‘emails:send‘)         ->daily()         ->pingBefore($url)         ->thenPing($url);

To install the pingBefore($url) thenPing($url) HTTP library guzzle, you can add the composer.json following line to the file to install the guzzle to the project:

"guzzlehttp/guzzle": "~5.3|~6.0"

[Laravel 5.1 Document] Service--Task scheduling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.