How to Create a Cron Job in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to create a cron job in Laravel.

 

How to Create a Cron Job in Laravel

 

Laravel Cron Job

To create a cron job in Laravel, you can use the built-in task scheduler provided by Laravel.

 

Here are the steps to create a new Laravel cron job:

 

Step 1 - Open the `App\Console\Kernel.php` file in your Laravel application.

 

Step 2 - Define a new command inside the `schedule()` method. For example, let's say you want to run a command named `mytask` every day at 3am:

protected function schedule(Schedule $schedule)
{
    $schedule->command('mytask')->dailyAt('03:00');
}

 

Step 3 - Create the command by running the following Artisan command:

php artisan make:command MyTaskCommand

This will create a new command file named `MyTaskCommand.php` inside the `app/Console/Commands` directory.

 

Step 4 - Open the `MyTaskCommand.php` file and add your custom logic inside the `handle()` method:

public function handle()
{
    // Your custom logic here
}

 

Step 5 - Test the command by running the following Artisan command:

php artisan mytask

This will run the command immediately, allowing you to test your custom logic.

 

Step 6 - Add the command to the crontab by running the following command:

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

This will add the command to your system's crontab, causing it to run automatically according to the schedule you defined in `Kernel.php`.

 

Note - the `schedule:run` command needs to be executed every minute for the Laravel task scheduler to work properly. The command redirects all output to `/dev/null` to avoid filling up log files.

Comments 0

Leave a comment