Basic laravel tutorial-Introduction to Task Scheduling
In the past, developers had to manually add a row in the schedule to input scheduled tasks. This is a headache, because you have to manually log on to the remote server to do these tasks, and it cannot be effectively controlled in the code. Laravel's command scheduler allows you to smoothly define your task plan in Laravel, and you only need to add a separate scheduled task entry to the server, then you can control the number of task plans in the code.
Your task plan is defined in the schedule method of the app/Console/Kernel. php file. Before starting, let's take a look at a simple example. You can add any task plan you want to execute in the Schedule object.
Start running plan
You only need to add the following entries in Cron of your server:
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
The Cron calls Laravel command scheduling every minute to execute the scheduled task. Laravel automatically evaluates your task plan and executes expired tasks.
Define a task
You can define all task plans in the schedule method of the App \ Console \ Kernel class. Before starting, let's take a look at a simple example of a task plan. In this example, we will execute Closure at midnight every day. In Closure, we will execute the query statement to clear the database table:
call(function () { DB::table('recent_users')->delete(); })->daily(); }}
In addition to scheduling Closure calls, you can also schedule Artisan commands and operating system commands. For example, you can use the command method to schedule an 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
Of course, there are various scheduling methods that can be assigned to the task:
Method |
Description |
-> Cron ('******'); |
Execute a custom Cron task plan |
-> EveryMinute (); |
Execute a task every minute |
-> EveryFiveMinutes (); |
Execute a task every five minutes |
-> EveryTenMinutes (); |
Execute a task every ten minutes |
-> Hourly (); |
Execute a task every hour |
-> Daily (); |
Execute a task at midnight every day |
-> DailyAt ('13: 00 '); |
Execute a task at every day |
-> TwiceDaily (1, 13 ); |
Execute a task at & every day |
-> Weekly (); |
Execute a task once a week |
-> Montyly (); |
Execute a task once a month |
-> MonthlyOn (4, '15: 00 '); |
The task is executed at every month. |
-> Quarterly (); |
Execute a task Quarterly |
-> Yearly (); |
Execute a task once a year |
-> Timezone ('America/New_York '); |
Set time zone |
These methods can be combined with additional restrictions to create more finely tuned plans, such as running only a few days of a week. Let's schedule a plan command to execute on Monday every 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 weekdays...$schedule->command('foo') ->weekdays() ->hourly() ->timezone('America/Chicago') ->when(function () { return date('H') >= 8 && date('H') <= 17; });
Additional plan constraints are listed below:
Method |
Description |
-> Weekdays (); |
Limited to normal days (except Saturday and Saturday) |
-> 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 true value test |
True value constraint
The when method can constrain the execution of a task based on the given true value test results. In other words, if the given Closure returns true, the task will be executed as long as other constraints do not prevent the execution of the task:
$schedule->command('emails:send')->daily()->when(function () { return true;});
The skip method is the opposite of the when method. If the skip method returns true, the scheduling task is not executed:
$schedule->command('emails:send')->daily()->skip(function () { return true; });
When the when method is chained, the scheduling task command is executed only when all the 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 scheduled every minute, but it will be executed again only when the command is not run in the process. The withoutOverlapping method is particularly effective for tasks that cannot determine the execution time, so as to avoid increasing pressure on the server by executing more and more time-consuming tasks at the same time.
Task output
Laravel's Task Scheduler provides a variety of convenient methods to generate the output of scheduled tasks. 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 selected email address. However, you must first use the sendOutputTo method to send the output to the file. In addition, you must configure laravel's email service before sending task output:
$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 calling the call method.
Task hook
You can use the before and after methods to perform specific operations when the 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 the specified URL before or after the task is completed. These methods are usually used to notify external services. For example, Laravel Envoyer informs him that the scheduled task is to be executed or has been completed:
$schedule->command('emails:send') ->daily() ->pingBefore($url) ->thenPing($url);
To use the pingBefore ($ url) or thenPing ($ url) method, you must introduce the Guzzle HTTP class library. You can use Composer for installation:
"guzzlehttp/guzzle": "~5.3|~6.0"