Task Scheduling Laravel example with Crontab

Task Scheduling
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Task Scheduling is one of the fancy features in a Laravel application. In this tutorial, I will show you how to implement Scheduling and artisan console with examples. Our example will be sent an email every midnight to unverified users. So here we go.

Task Scheduling

Task Scheduling Laravel example with Crontab

Well, I will show you everything step by step. But before jumping to implementation first, you have to know what is artisan console is.

What is Artisan Console?

Artisan Console is the name of the CLI included with Laravel. It provides a number of helpful commands for your use while developing your application/software. It is driven by the powerful Symfony Console component.

Read More : The magic of Laravel Collection Macro and Mixins

Well, I assume you have a users table and where a filed is is_verified. If you don’t have then you have to edit your users migrations file.

   $table->boolean('is_verified')->default(false);

Well, Then run the migrations command so that it will created this column. Well, now you have to create an artisan command by this code. Run this code in your project’s terminal.

php artisan make:command SendNotVerifiedEmailCommand

After then, Run this command, a new Command file has been created in the App\Console\Commands directory.

App\Console\Commands\SendNotVerifiedEmailCommand.php

Now, in this class file, you may see two protected variables “signature”, “description” where you have to set up your command name and describe your command.

 protected $signature = 'send:mail';
 protected $description = 'Send mail to unverified users'';

Well, now you have to define your logic in handle() method like this. Before you have to make an Email class send an email. Follow this below code to create a mail.

php artisan make:mail SendUnVerifiedEmail

Task Scheduling

Then, go to app/Mail folder. You can see all the mail classes that you have created for your applicaions. Well, your mail class looks like the below code.


class SendUnVerifiedEmail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public $user;
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('Unverified Account!')
            ->view('mail.unverified');
    }
}

Well, now you can write your logic inside the handle() method. Copy and paste the below code in your handle method.

app/console/command/SendNotVerifiedEmailCommand.php
  public function handle()
    {
        $users = User::whereIsVerified(0)->get();
        foreach ($users as $user) {
            Mail::to($user->email)->send(new SendUnVerifiedEmail($user));
            $this->info("Email has been sent on {$user->name}!");
        }
    }

Next, Now you have to register for this command App\Console\Kernel class. go there and register your command in the $commands array.

Task Scheduling

App\Console\Kernel

 protected $commands = [
        SendNotVerifiedEmailCommand::class
    ];

then you have to set a schedule for how many times you want to run your command.

 protected function schedule(Schedule $schedule)
    {
        $schedule->command('send:mail')->daily();
    }

You can add more time like everyTwoMinutes(), everyThreeMinutes(), everyFiveMinutes(), everyThirtyMinutes(), hourly(), hourlyAt(17), daily().

Well, now time to test our artisan command using crontab. You have to run this code in your terminal for implement crontab settings.

sudo crontab -e

Then you can see an interface like this image.

crontab

You can delete this code if you want. Then after you have pasted this code for the cron job. Looks below code.

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

Then you have o give your project path. You can get your project path using this command. Run this command in your project’s folder

pwd
 /home/shahin/Desktop/Laravel/relationships // output

Then edit your crontab command like this.

* * * * * cd /home/shahin/Desktop/Laravel/relationships && php artisan schedule:run >> /dev/null 2>&1

Well, now you can test your cronjob. Hope it will help you.

Read More : How to implement Redis Cache in Laravel 8.x

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

Leave a Reply

Your email address will not be published. Required fields are marked *