Laravel Basic Tutorial--mission plan

Source: Internet
Author: User

Task Scheduler (scheduling)

Brief introduction

In the past, developers needed to manually add a line to the schedule to enter scheduled tasks. This is very annoying, because you have to manually log on to the remote server to do these things, it is not in the code to effectively control. Laravel's command dispatcher allows you to define your task plan fluently and smoothly in Laravel, and you only need to add a separate scheduled task entry to the server for this purpose, and then you can control the number of scheduled tasks in your code.

Your task plan is defined in the schedule method of the app/console/kernel.php file. Before we begin, let's look at a simple example. You can add any task plan you wish to perform in the Schedule object.

Start a Run Schedule

You only need to add the following entries to your server's Cron entry:

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

The Cron calls Laravel's command schedule every minute to perform scheduled tasks. Laravel will automatically evaluate your task schedule and perform the tasks that expire.

Defining tasks

You can define all the task schedules in the schedule method of the App\console\kernel class. Before we start, let's look at a simple example of a task plan. In this example, we will execute the Closure at midnight every day. In Closure we execute the query statement that clears the database table:

 
  Call (function () {        db::table (' recent_users ')->delete ();      }) ->daily ();    }}

In addition to scheduling Closure calls, you can also dispatch Artisan commands and operating system commands. For example, you can use the command method to dispatch a Artisan command:

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

You can use the Exec method to publish a command to the operating system:

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

Scheduling frequency Options

There are, of course, a variety of scheduling methods that can be assigned to tasks:

Method Description
->cron (' * * * * * * * '); Perform a custom Cron task schedule
->everyminute (); Perform a task once per minute
->everyfiveminutes (); Perform tasks every five minutes
->everytenminutes (); Perform tasks every 10 minutes
->hourly (); Perform a task every hour
->daily (); Perform one task at midnight every day
->dailyat (' 13:00 '); 13:00 per day to perform a task
->twicedaily (1, 13); Perform a task once a day AT & 13:00
->weekly (); Perform a task once a week
->montyly (); Perform a task once a month
->monthlyon (4, ' 15:00 '); 4th number 15:00 per month perform a task
->quarterly (); Perform a task once per quarter
->yearly (); Perform a task once a year
->timezone (' america/new_york '); Setting the time zone

These methods can be combined with additional constraints to create a more nuanced plan, such as running only in a few days of the week. Let's schedule a scheduled command to be executed in Monday of the week:

Run once per week on Monday at 1 PM ... $schedule->call (function () {  //})->weekly ()->mondays ()->at (' 13:00 ');//Run hourly from 8 AM to 5 PM on we Ekdays. $schedule->command (' foo ')         ->weekdays ()         ->hourly ()         ->timezone (' america/ Chicago ')         ->when (function () {           return date (' h ') >= 8 && date (' h ') <=;         });

The additional schedule constraints are listed below:

Method Description
->weekdays (); Restricted within normal days (except Sunday Six)
->sundays (); Limited to Sunday
->mondays (); Limited to Monday
->tuesdays (); Limited to Tuesday
->wednesdays (); Limited to Wednesday
->thursdays (); Limited to Thursday
->fridays (); Limited to Friday
->staturdays (); Limited to Saturday
->when (Closure); Limit based on truth testing

Truth constraint

The When method can constrain the execution of a task based on the results of a given truth test. In other words, if the given Closure returns TRUE, the task will be executed as long as the other constraints do not prevent the execution of the task:

$schedule->command (' Emails:send ')->daily ()->when (function () {  return true;});

The Skip method is just the opposite of when. If the Skip method returns True, the dispatch task will not execute:

$schedule->command (' Emails:send ')->daily ()->skip (function () {  return true;});

When a chained call to the When method, the dispatch task command is executed only if all when constraints return true.

Avoid overlapping tasks

By default, if the previous task is still in progress, the scheduled task will run again. You can use the Withoutoverlapping method to avoid this:

$schedule->command (' Emails:send ')->withoutoverlapping ();

In this example, the Emails:send Artisan command is dispatched every minute, but it is not executed again until the command is run in the process. The Withoutoverlapping method is particularly effective for tasks that cannot determine the execution time, so you can avoid increasing the pressure on the server by doing more and more time-consuming tasks at the same time.

Task output

Laravel's task plan provides a number of convenient ways to generate the output of a scheduled task. First, you need to use the Sendoutputto method, you can pass a file path to the method for subsequent checks:

$schedule->command (' emails:send ')         ->daily ()         ->sendoutputto ($filePath);

If you want to append content to a given file, you should use the Appendoutputto method:

$schedule->command (' emails:send ')         ->daily ()         ->appendoutputto ($filePath);

You can use the Emailoutputto method to send the output to the mailbox address you selected. But you need to be aware that you must first use the Sendoutputto method to send the output to a file. Also, before sending the output of the task through the mail, you need to configure the Laravel mail Service first:

$schedule->command (' foo ')         ->daily ()         ->sendoutputto ($filePath)         ->emailoutputto (' Foo@example.com ')

Note: The Emailoutputto and Sendoutputto methods can only be executed in the command method and do not support calls to call methods.

Task Hooks

You can use the before and after methods to perform specific actions when a task is scheduled to be executed or completed:

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

Pingings URLs

With the Pingbefore and Thenping methods, task scheduling can automatically ping a given URL before or after the task is completed. These methods are often used to inform external services. Laravel Envoyer, for example, informs that the scheduled task will be executed or has been completed:

$schedule->command (' emails:send ')         ->daily ()         ->pingbefore ($url)         ->thenping ($url);

Using the Pingbefore ($url) or thenping ($url) method requires the introduction of the Guzzle HTTP class library. You can install via Composer:

"Guzzlehttp/guzzle": "~5.3|~6.0"
  • 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.