LoginSignup
35
43

More than 5 years have passed since last update.

Laravel タスクスケジュール作成の一連の流れ

Last updated at Posted at 2018-08-30

概要

Laravelでcronから実行する処理の作成をまとめました。

作成方法

1.コマンドのクラス作成

処理を記述するクラスを作成

$ cd {path_to_project}
$ php artisan make:command TestCommand

2.処理の追加

1で作成されたクラスに処理を追加
コマンド名、コマンドの説明を変更し、処理を追加します。

path_to_project/app/Console/Commands/TestCommand.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class TestCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    //コマンド名を設定(元:command:name→変更後:command:testcommand)
    protected $signature = 'command:testcommand';  

    /**
     * The console command description.
     *
     * @var string
     */
    //コマンドの説明(元:Command description→変更後:testcommandのコマンド説明)
    protected $description = 'testcommandのコマンド説明';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

         // ここに処理を記述
         echo "testcommand実行!!\n";
    }
}

3.コマンドの登録、スケジュールの登録

記述した処理のコマンド登録、cronで実行するスケジュールの登録

path_to_project/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 = [
        \App\Console\Commands\TestCommand::class,   //コマンドの登録

    ];


    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // スケジュールの登録(「->daily()」は毎日深夜12時に実行)
        $schedule->command('command:testcommand')->daily();
    }

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

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

4,登録したコマンドの確認

コマンドが登録されているかリストより確認

 $ php artisan list

...(中略)

 command
  command:testcommand          testcommandの説明  

...(中略)

5,コマンド実行

登録したコマンドを実行

$  php artisan command:testcommand
testcommand実行!!

6,cronにエントリの追加

毎分Laravelのコマンドスケジューラを呼び出すよう、以下のエントリを追加

$ crontab -e

* * * * * php /{path_to_project}/artisan schedule:run >> /dev/null 2>&1

これで登録したスケジュール通りにコマンドが実行されるようになります。

35
43
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
43