롸?

라라벨 스케줄러 & 크론탭 설정하기 본문

Framework/Laravel

라라벨 스케줄러 & 크론탭 설정하기

허니버터새우깡 2021. 12. 21. 17:55

라라벨 스케줄러를 이용해서 스케줄링이 필요한 작업을 코드로 작성하고 크론잡을 등록해서 예약된 시간에 작업이 실행되도록 할 수 있다.

사전에 크론이 설치되고 서비스가 실행되고 있어야 한다.

 

1. artisan 명령어를 통해 라라벨 커맨드를 생성

php artisan make:command 클래스명

 

해당 명령어 실행 시 /app/Console/Commands/클래스명.php 클래스파일이 생성된다.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class 클래스명 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 mixed
     */
    public function handle()
    {
        //
    }
}

 

파일 안에서 handle 메소드에 동작할 내용을 정의한다.

 

2. 커널에 command 등록

Command가 실행되기 위해서는 /app/Console/Kernel.php 에 등록되어야 한다.

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        클래스명::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command(클래스명::class)->hourly();
    }

schedule메소드에 실행될 작업에 추가적인 제한들을 조합하여 세밀한 스케줄을 생성할 수 있다.

 

3. Artisan 콘솔로 signature 명으로 테스트를 해 볼 수 있다.

php artisan command:name

 

4. 크론탭 설정을 한다

$crontab -e  
# * * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1 를 작성

크론탭 편집기를 열어서 위와 같은 내용을 추가하여도 되고

 

$ echo "* * * * * cd /var/www/html/pinenote-rpa-bpo-auth-server && php artisan schedule:run >> /dev/null 2>&1" >> /etc/cron.d/{크론잡 파일명}
$ crontab /etc/cron.d/{크론잡 파일명}

 별도의 경로와 파일에 크론잡을 생성하여서 크론에 추가하는 방식도 가능

 


참고 

1.  https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=rladlaks123&logNo=221264135597

2.  https://laravel.kr/docs/5.8/scheduling

 

'Framework > Laravel' 카테고리의 다른 글

라라벨 예외처리  (0) 2022.04.01
라라벨 브로드캐스팅 & 라라벨 에코 서버  (0) 2021.12.10
쿼리빌더와 엘로퀀트  (0) 2021.11.26
미들웨어  (0) 2021.11.18
라이프사이클  (0) 2021.11.18
Comments