Laravelのスケジュール覚書、初心を忘れずに。#chatGPTの罠

20230418

Logging

おはようございます、laravelのスケジュールを触ってみて。躓いた点は一点だけ。スケジュールリストに登録されているけど、動作しなかった。chatGPT3の罠に引っかかりました。chatGPTはもっともらしいコードを書いてくれるけど、たまに動作しないコードも出力されます。それにまんまと引っかかり、沼から出てこれなくなる所でした。

Laravelはお利口さんだから、上手くやってくれるだろうとJob側のコンストラクタには何も記述しなかったのが間違い。コマンドで行わない場合は下記の記述は絶対らしい。

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;

class WebsiteMonitor implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
    }
    public function __invoke()
    {
        $this->handle();
    }
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
     //行いたい処理🐺
    }
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Jobs\WebsiteMonitor;
class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // どちらでもOK👉 $schedule->job(new WebsiteMonitor)->everyFifteenMinutes();
        $schedule->call(function () {
            dispatch(new WebsiteMonitor());
        })->everyFifteenMinutes();
    }

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

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

行いたい処理を書いたら、カーネルに処理を登録してcronに下記のように記述する。

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

これで処理が定期的に実行されます。尚、参考サイトとしてこちらに詳しい情報が書かれています。

タグ

call, ChatGPT, construct, cron, dev, DIR, dispatch, everyFifteenMinutes, handle, IlluminateConsoleSchedulingSchedule, InteractsWithQueue, Laravel, load, PARAM, Queueable, routes, Schedule, SerializesModels, コンストラクタ,