andriajah Tue Jul 2022 1 year ago

Membuat Schedule Tasks dengan Cron Job di Laravel

Sepanjang tutorial ini, Anda akan belajar bagaimana task schedule di aplikasi Laravel menggunakan Cron Job.

Task Schedule adalah seni mengatur prioritas Anda secara sistematis untuk mencapai tujuan Anda tepat waktu, di sisi lain, Cron Job adalah utilitas perangkat lunak yang digunakan untuk menjadwalkan tugas tertentu agar berjalan secara berkala dalam aplikasi perangkat lunak.

Anda dapat menjadwalkan tugas dengan pekerjaan Cron di laravel, dengan cara yang sama, membangkitkannya secara berkala. Untungnya, laravel menawarkan Anda pengelola tugas yang kuat yang mengatakan bahwa Anda akan melihat cara menggunakannya di lingkungan laravel dengan benar.

Juga, Anda akan mengetahui cara membuat perintah artisan baru, singkatnya tentang perintah laravel kustom, cara mendaftarkan penjadwal tugas baru di file kernel laravel, cara menangani penjadwal tugas secara efektif tidak hanya tetapi juga cara menjalankan penjadwal tugas laravel dari awal yang sama sekali.

Buat Proyek Laravel

Mulailah dengan menginstal proyek Laravel baru untuk task schedule cron job:

composer create-project laravel/laravel laravel-task-schedule-example --prefer-dist

Hubungkan Laravel ke Database

Tambahkan nama database, nama pengguna dan kata sandi dalam file .env :

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=

Hasilkan Perintah Artisan Baru

Artisan adalah antarmuka baris perintah yang disertakan dengan Laravel; Anda dapat membangun seluruh aplikasi Anda dengan perintah yang berguna. Demikian juga, untuk membuat perintah baru, Anda dapat menggunakan make:command, Ini akan menghasilkan kelas perintah di folder app/Console/Commands.

php artisan make:command DailyMessage

Di sisi lain, Anda dapat memeriksa file app/Console/Commands/DailyMessage.php di mana Anda dapat mendaftarkan perintah cron job baru untuk task schedule.

<?php

namespace App\Console\Commands;
use Illuminate\Console\Command;

class DailyMessage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:name';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        return 0;
    }
}

Siapkan Perintah Kustom Laravel

Buka file app/Console/Commands/DailyQuote.php, Di tempat kedua, Ganti kode saat ini dengan kode yang diberikan di bawah ini.

<?php

namespace App\Console\Commands;
use Illuminate\Console\Command;

use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;
use App\Models\User;

class DailyMessage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'daily:message';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send best wishes daily.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $messages = [
            'A. A. Milne' => 'People say nothing is impossible, but I do nothing every day.',
            'Abraham Lincoln' => 'Better to remain silent and be thought a fool than to speak out and remove all doubt.',
            'Abraham Lincoln' => 'If I were two-faced, would I be wearing this one?',
            'Al McGuire' => 'The only mystery in life is why the kamikaze pilots wore helmets.',
            'Alan Dundes' => 'Light travels faster than sound. This is why some people appear bright until you hear them speak.',
            'Albert Camus' => 'Nobody realizes that some people expend tremendous energy merely to be normal.'
        ];
         
        // Setting up a random word
        $key = array_rand($messages);
        $data = $messages[$key];
         
        $users = User::all();
        foreach ($users as $user) {
            Mail::raw("{$key} -> {$data}", function ($mail) use ($user) {
                $mail->from('[email protected]');
                $mail->to($user->email)
                    ->subject('Good morning!');
            });
        }
         
        $this->info('Message sent.');
    }
}

Register Task Scheduler Command

Sampai di atas kami telah membuat dan membuat perintah khusus untuk menjadwalkan tugas. Sekarang, Anda harus mendaftarkan perintah task scheduler baru di file app/Console/Kernel.php.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\DailyMessage::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('daily:message')
        ->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

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

Jika Anda menggunakan perintah yang diberikan di bawah ini maka Anda juga dapat melihat perintah yang baru saja Anda buat:

cache
  cache:clear          Flush the application cache
  cache:forget         Remove an item from the cache
  cache:table          Create a migration for the cache database table
 config
  config:cache         Create a cache file for faster configuration loading
  config:clear         Remove the configuration cache file
 daily
  daily:message        Send best wishes daily.
 db
  db:seed              Seed the database with records
  db:wipe              Drop all tables, views, and types
 event
  event:cache          Discover and cache the application's events and listeners
  event:clear          Clear all cached events and listeners
  event:generate       Generate the missing events and listeners based on registration
  event:list           List the application's events and listeners
 key
  key:generate         Set the application key

Anda dapat menggunakan perintah di bawah ini untuk menjadwalkan tugas Anda dengan cron job:

php artisan daily:message

Jika semuanya berjalan dengan baik, ini akan terlihat di layar konsol Anda:

Message sent.

Atur Jadwal Frequent dengan Beberapa Pilihan

Seperti yang Anda ingat, Anda menggunakan frekuensi everyMinute() dalam jadwal:

Running scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' daily:message > '/dev/null' 2>&1
 protected function schedule(Schedule $schedule)
    {
        $schedule->command('daily:message')
        ->everyMinute();
    }

Karena itu, ada banyak sekali schedule yang dapat Anda tetapkan untuk task cron Anda di Laravel .

Run Task Scheduler

Anda memiliki dua opsi untuk menjalankan task scheduler secara manual atau otomatis.

Jadi, mulailah dulu dengan cara manual.

php artisan schedule:run

Jika bekerja dengan benar maka itu akan ditampilkan di konsol Anda:

Running scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' daily:message > '/dev/null' 2>&1

Lihat log di file storage/logs/laravel.php.

Selanjutnya, Anda juga dapat mengotomatiskan task scheduler untuk task cron.

 

Mari kita mengotomatiskan task scheduler Laravel:

SSH ke server Anda untuk menambahkan entri Cron tambahan:

crontab -e

Sekarang, tambahkan path lengkap di dalam file crontab aplikasi Anda:

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

Tutorial Laravel Cron Job sudah berakhir sekarang Anda tahu cara mudah menjadwalkan tugas di aplikasi Laravel.

laravel task scheduler laravel laravel cron job example