Detailed explanation of scheduled tasks in laravel5.5 (demo)

1, Prepare the environment

The server: linux(debian)+nginx+mysql+php environment
 Frame: laravel 5.5 (Confirm that it can run through)
Demand: perform scheduled operation at 1:00 p.m. every day

2, To schedule a task

1. Create commands based on documents

First, enter the laravel/app/console directory. The Console directory contains all customized Artisan commands. These command classes can be generated by using the make:command command command. There are also Console/Kernel classes under this directory, where you can register custom Artisan commands and define scheduling tasks.

For example, we create a scheduled task named Test:

//Here, the php artisan given by laravel is used to generate commands, and the Test here is the file we want to generate
//The artisan here represents not only the commands provided by laravel, but also the artisan directory under laravel. Because this directory does not have x, that is, executable permissions, it cannot be used/ Artisan, which can only be executed through php
php artisan make:command Test

2. After creation, open the commands directory under the console directory, and we will find that there is already a file in it

The approximate code is as follows:

<?php

namespace App\Console\Commands;

use App\Services\CalculateDataService;
use Illuminate\Console\Command;

class Test extends Command
{
    //This represents the name automatically generated by laravel, which can be used in the following execution
    protected $signature = 'test:data';

    //This represents a description, which is useless
    protected $description = 'test data';

    /**
     * Calculate the service property of the data service
     *Since our logic will be used here, please define it in advance for the convenience of the following use
     * @var CalculateDataService
     */
    protected $service;

   //This is the construction method of laravel. It is empty in the initial state.
   //Since I want to call a method of the CalculateDataService class, I introduced it in the way of dependency injection.
    public function __construct(CalculateDataService $service)
    {
        parent::__construct();

        $this->service = $service;
    }

    /**
     * Execute the console command.
     *This is the place where we perform operations. It contains the business to be processed by the command. According to our needs,
     *Call the calculateData () method in the class, which is part of our own requirements logic.
     * @return mixed
     */
    public function handle()
    {
        try {
            $this->service->calculateData();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        //  The line() method is a self-contained method in the command class, which can output our customized information
        $this->line('calculate Data Success!');
    }
}

3. After the timer command is created, we need to modify the kernel PHP file

kernel. In the PHP file, it mainly defines the scheduling time of commands and the execution order of commands.

For this part, please refer to the official documents of laravel:
http://laravelacademy.org/post/8484.html

4. My kernel PHP file

<?php
//The namespace section is omitted here
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *Note: here is the introduction of our newly created class. Since we use the command name here, we do not use this class name. However, comparative standards are introduced
     * You can use the command method to schedule an Artisan command by command name or class:
     * $schedule->command('emails:send --force')->daily();
     * $schedule->command(EmailsCommand::class, ['--force'])->daily();
     *
     * @var array
     */
    protected $commands = [
        Test::class,
        CalculateData::class,
        UpdateOffset::class,
    ];

    /**
     * Define the application's command schedule.
     * Note:
     * 1,This method determines the execution sequence of timing methods according to its own needs. Control through keywords such as after and before
     * 2,This is equivalent to specifying the agreed scheduled execution time. For example, the following scheduled tasks are executed at 0:30
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // Execute the task of synchronizing aliyun data at 0.45 a.m. every day and send an email to***
         $schedule->command('iot:sync Flow')
            ->after(function() {
                 //Update the offset. No parameters can be added to after
                Artisan::call('Test:data');
            })
            ->after(function () {
                // Execute the calculate data task after the synchronize data command is completed
                Artisan::call('calculate:data');
             });
    }

    /**
     * Register the commands for the application.
     * //This part is automatically generated by laravel, and the command file we generated is introduced
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

For the specific scheduling method schedule (), you can go to the laravel document, which can specify many things. Here is the hook function used. When multiple scheduled tasks are to be executed at the same time, multiple scheduled tasks can be orderly through after, before and other methods.

3, Execute our timing

Although the scheduled task of laravel has always been said to be very powerful, it is essentially inseparable from the cron script on the server..

1. View the scheduled entries on the server first

crontab -l

2. Add or edit cron entries

crontab -e

3. Add the method path we have written

Our regular tasks are added to this.

The first is to specify the execution time of scheduled tasks
 The second is to artisan Directory path write pair
 third schedule:run Is to execute the task scheduling we wrote before, that is kernel.php In the file schedule method.

If you are testing by yourself, you can write a scheduled task at will and execute the following tasks every minute, so that you can accurately know whether your scheduled task is correct.

end

Tags: Laravel

Posted by Blob on Thu, 02 Jun 2022 09:02:59 +0530