-2

Làm thế nào để cài đặt cron job tự động (Task Scheduling) trong laravel

Chắc hẳn trong các dự án đôi lúc các bạn sẽ phải thực hiện một số công việc hàng ngày, hàng tuần, hàng tháng ...
Chính vì vậy để thực hiện những công việc đó một cách tự động thì laravel đang sử dụng task scheduler để chạy các job tự động theo một lịch trình mà ta sắp đặt.
Bài viết này mình sẽ hướng dẫn các bạn từng bước cách cài đặt cron job với task scheduler trong laravel.

Bước 1: Install laravel

Trong bước này, nếu bạn chưa có ứng dụng laravel thì ta sẽ tải về ứng dụng laravel 7. Vì thế hãy chạy lệnh dưới đây để tải ứng dụng laravel 7 về:

composer create-project --prefer-dist laravel/laravel blog

Bước 2: Tạo migration

Ở đây chúng ta cần tạo migration cho bảng tasks

php artisan make:migration create_tasks_table

Migration

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreateTasksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('title')->nullable();
            $table->string('type')->nullable();
            $table->string('frequency')->nullable();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tasks');
    }
}

Chạy lệnh dưới đây để sinh ra bảng tasks.

php artisan migrate

Bước3: Tạo model

Bây giờ chúng ta sẽ tạo ra model Task sử dụng lệnh dưới đây:

php artisan make:model Task

App/Task.php

<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
  
class Task extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'type', 'frequency',
    ];
}

Bước 4: Tạo seeder

Chúng ta sẽ tạo ra file seeder để tạo ra những dữ liệu mẫu cho bảng tasks . Chạy lệnh dưới đây:

php artisan make:seeder CreateTask

database/seeds/CreateTask.php

<?php
  
use Illuminate\Database\Seeder;
use App\Task;
  
class CreateTask extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $tasks = [
            [
                'title' => 'It will run every minute',
                'type' => 'everyMinute',
                'frequency' => 'everyMinute'
            ],
            [
                'title' => 'It will run every five minute',
                'type' => 'everyFiveMinutes',
                'frequency' => 'everyFiveMinutes'
            ],
            [
                'title' => 'It will run daily',
                'type' => 'daily',
                'frequency' => 'daily'
            ],
            [
                'title' => 'It will run every month',
                'type' => 'monthly',
                'frequency' => 'monthly'
            ]
        ];
  
        foreach ($tasks as $key => $task) {
            Task::create($task);
        }
    }
}

Bây giờ chạy file seeder đã tạo bằng lệnh dưới đây:

php artisan db:seed --class=CreateTask

Bước 5: Cài đặt tự động Task Scheduling

Bây giờ trong bước này chúng tôi sẽ cài đặt logic cron job tự động trong file Kernel.php.
Thêm nội dung dưới đây vào file.
app/Console/Kernel.php

<?php
  
namespace App\Console;
  
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Task;
use Log;
  
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        'App\Console\Commands\DatabaseBackUp'
    ];
  
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        /* Get all tasks from the database */
        $tasks = Task::all();
  
        foreach ($tasks as $task) {
  
            $frequency = $task->frequency;
  
            $schedule->call(function() use($task) {
                /*  Run your task here */
                Log::info($task->title.' '.\Carbon\Carbon::now());
            })->$frequency();
        }
    }
  
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
  
        require base_path('routes/console.php');
    }
}

Và bây giờ chúng đã sẵn sàng để thiết lập scheduler trên crontab. Hãy chạy lệnh dưới đây trên server.

crontab -e

Lệnh trên sẽ mở ra file Crontab của server và thêm lệnh dưới đây vào file đó với đường dẫn gốc của dự án.

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

Bây giờ , nó đã chạy một cách tự động.
Bạn có thể kiểm tra output trong file log như dưới đây: Chúc các bạn thành công!

Bài viết được lược và dịch từ: https://www.itsolutionstuff.com/post/how-to-setup-dynamic-cron-jobtask-scheduling-in-laravelexample.html


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí