Home » How To Schedule Tasks In Laravel With Example

How To Schedule Tasks In Laravel With Example

Last updated on May 21, 2022 by

In this article, we will see how to schedule tasks in Laravel. I will give you step by step walk-through of how to schedule tasks in the Laravel task scheduling. This tutorial will show you how to set up a cron job in Laravel with a simple example. Let’s just dive into it.

Sometimes, we have a question in our minds. Why do we need to use the corn job, and what are its benefits? If you have these questions in your mind then you are at the right place.

Task schedulers are useful to automate the process in the background without the need for any user interactions. For eg. Sending emails every minute or hours, Sending notifications, Generating reports every month-end or weekly, etc. Hope you understood the use of scheduler in Laravel. Let’s see how to set up it in Laravel.

Step 1: Install Laravel

Skip this step if you have already installed Laravel. Run the below command to install the latest version of Laravel.

composer create-project --prefer-dist laravel/laravel blog

Step 2: Create A Command

In this step, we will create a new Artisan custom command which will execute the task as per our set timing. This command will also be visible if you just run the php artisan in your command-line interface. Let’s just run the below command to create a new custom command.

php artisan make:command SendEmails --command=emails:send

After running the above command, a new file will be created in app/Console/Commands/SendEmails.php directory.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SendEmails extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'emails:send';

    

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sends email to inactive users';

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

    }
    
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $inactiveUsers = User::where('status', 'inactive')->get();

        foreach ($inactiveUsers as $user) {
            Mail::to($user)->send(new InactiveUsers($order));
        }
    }
}

In the handle()method, we are sending emails to inactive users. You can simply create the mailable using the below command:

php artisan make:mail InactiveUsers

Step 3: Register as Task Schedule In Laravel

In this step, we will register our newly created command on app/Console/Kernel.php file with the specific time when you want to run your command as below:

MethodDescription
->cron('* * * * *');Run the task on a custom cron schedule
->everyMinute();Run the task every minute
->everyTwoMinutes();Run the task every two minutes
->everyThreeMinutes();Run the task every three minutes
->everyFourMinutes();Run the task every four minutes
->everyFiveMinutes();Run the task every five minutes
->everyTenMinutes();Run the task every ten minutes
->everyFifteenMinutes();Run the task every fifteen minutes
->everyThirtyMinutes();Run the task every thirty minutes
->hourly();Run the task every hour
->hourlyAt(17);Run the task every hour at 17 minutes past the hour
->everyTwoHours();Run the task every two hours
->everyThreeHours();Run the task every three hours
->everyFourHours();Run the task every four hours
->everySixHours();Run the task every six hours
->daily();Run the task every day at midnight
->dailyAt('13:00');Run the task every day at 13:00
->twiceDaily(1, 13);Run the task daily at 1:00 & 13:00
->weekly();Run the task every Sunday at 00:00
->weeklyOn(1, '8:00');Run the task every week on Monday at 8:00
->monthly();Run the task on the first day of every month at 00:00
->monthlyOn(4, '15:00');Run the task every month on the 4th at 15:00
->twiceMonthly(1, 16, '13:00');Run the task monthly on the 1st and 16th at 13:00
->lastDayOfMonth('15:00');Run the task on the last day of the month at 15:00
->quarterly();Run the task on the first day of every quarter at 00:00
->yearly();Run the task on the first day of every year at 00:00
->yearlyOn(6, 1, '17:00');Run the task every year on June 1st at 17:00
->timezone('America/New_York');Set the timezone for the task

Let’s open the app/Console/Kernel.php file and register our command to run every day at 12:00 AM night.

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\SendEmails::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('emails:send')
                 ->dailyAt('24:00');
    }

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

Step 4: Test Laravel Scheduler Command

Now, we are all set to run the schedule laravel command. Typically, you would not add a scheduler cron entry to your local development machine. Instead, you may use the schedule:work Artisan command. This command will run in the foreground and invoke the scheduler every minute until you terminate the command:

php artisan schedule:work

After running the above command, all the users who are inactive will receive an email. You can also set a flag in the database to check email is already been sent or not.

Step 5: Running The Scheduler On Server

Now, if you want to set this cron on your server then you just need to open the server’s crontab file using crontab -e and copy-paste the below command into it:

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

OR OR OR OR OR

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1

Additionally, read our guide:

  1. Laravel: Blade Switch Case Statement Example
  2. Laravel: Switch Case Statement In Controller Example
  3. Laravel: Change Column Type In Migration
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Update Pivot Table In Laravel
  11. How To Dynamic iFrame URL In Elementor
  12. How To Handle Failed Jobs In Laravel
  13. How To Remove WooCommerce Data After Uninstall
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration
  18. How To Fix Elementor Icons Not Showing
  19. Laravel Video Upload Tutorial With Example

That’s it from our end. We hope this article helped you to learn how to schedule tasks in Laravel

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment