Laravel Cron Jobs Scheduling To Make Automation Easier

To automate these tasks, a task scheduling system is required. Laravel Cronjob offers an elegant Task Scheduling or Laravel Cronjob Scheduling mechanism. For example, it could be sending promotional emails, optimizing the database, creating backups, or generating site traffic reports.

What is Cronjob?

Cron is a UNIX-like system task scheduler that runs shell commands at specified intervals.

If we want to schedule tasks that will be executed often, we need to edit the Crontab. Crontab is a file that contains a list of scripts that will run periodically. 

Cron is a task scheduler daemon that runs scheduled tasks at specific intervals. Cron uses the configuration file called Crontab, the cron table, to manage the scheduling process.

Crontab contains cronjobs, each related to a specific task. Cronjobs are composed of two parts.

  1. Cron expression
  2. Shell command to be run.
* * * * * shell command to run

So what we do here is create the command using Laravel Console and then schedule that command at a particular time. You only need to add the following Cron entry to your server when using the scheduler.

Laravel Cronjob Scheduling

Laravel CronJob is a built-in task manager that allows your app to execute specific commands like sending notification or removing inactive users periodically. Applications require some tasks to be run regularly on the server.

We need specific administrative tasks that run periodically in any web application, and doing that manually is not a good idea. In addition, applications require some tasks to be run regularly on the server.

For example, it could be creating backups, generating site traffic reports, sending promotional emails, or optimizing the database.

Whether you want to email your customers about particular events or clean up the database tables at a specific time, you will need a task-scheduling mechanism to take care of the tasks.

Here are the steps to set up cron jobs scheduling:

Step 1: Configuring the Laravel.

Type the following to generate the boilerplate of Laravel.

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

Now edit the .env file to configure the database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cron
DB_USERNAME=root
DB_PASSWORD=

Migrate the tables into the database.

php artisan migrate

Step 2: Create the Laravel Artisan Command.

We use the make: console Artisan command to generate a command class skeleton to work with.

In this application, we will send one email to the owner telling us that we have this number of users registered today. So please type the following command to generate our console command.

php artisan make:command RegisteredUsers --command=registered:users

The above command will create a class named RegisteredUsers in a file of the same name in the app/Console/Commands folder.

We have also picked a name for the command via the command option. It is the name that we will use when calling the command. Now, open that command file RegisteredUsers.php.

   /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send an email of registered users';

We have just changed the description of the command. Register this command inside the app  >>  Console >> Kernel.php file.

 /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        'App\Console\Commands\RegisteredUsers',
    ];

Go to the terminal and hit the following command.

php artisan list

You can see in the list that your newly created command has been registered successfully. We just now called in via CronJob and got the job done. Write the handle method to get the number of users registered today.

// RegisteredUsers.php

 /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $totalUsers = \DB::table('users')
                  ->whereRaw('Date(created_at) = CURDATE()')
                  ->count();
    }

Next step, we need to send an email that contains that totalUsers. So let’s create a mail class.

Step 3: Create a mailable class to send the mail.

Type the following command to generate a mail class.

php artisan make:mail SendMailable

It will create this file inside App\Mail\SendMailable.php. Now, this class contains one property, and that is count. This count is the number of users that registered today. So the SendMailable.php file looks like this.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendMailable extends Mailable
{
    use Queueable, SerializesModels;
    public $count;

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

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.registeredcount');
    }
}

Define the view for this mail at resources  >>  views  >> emails  >>  registeredcount.blade.php file. The mails folder is not there, so we must create one and add the view registeredcount.blade.php.

<div>
    Total number of registered users for today is: {{ $count }}
</div>

Add this mailable class inside the RegisteredUsers.php file.

// RegisteredUsers.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMailable;

class RegisteredUsers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'registered:users';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send an email of registered users';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $totalUsers = \DB::table('users')
                  ->whereRaw('Date(created_at) = CURDATE()')
                  ->count();
        Mail::to('krunal@appdividend.com')->send(new SendMailable($totalUsers));
    }
}

For sending mail, I have used Mailtrap. You can quickly signup there. It is free for some users. Moreover, it fakes email, so it is convenient to test our application.

Please type the following command to execute our code. But first, let us see if we can get the mail.

php artisan registered:users

Zoinks, we are getting the email saying that the Total number of registered users for today is: 1.

Task Scheduler in Laravel

Task Scheduler in Laravel executes the artisan command, shell, or a callback periodically on the defined time. To do this, we use the schedule method in app/Console/Kernel.php, as discussed earlier.

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

The $schedule->command(‘registered:users’) is where we define which command needs to be executed, and ->daily(); defines the frequency of execution.

There are some more time intervals that we can define. For example, you can replace ->daily(); with another time interval option from the following list.

You can find more about Task Scheduling in Laravel Documentation.

Method Description
->cron(‘* * * * * *’); Run the task on a custom Cron schedule
->everyMinute(); Run the task every minute
->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 mins past the hour
->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 week
->weeklyOn(1, ‘8:00’); Run the task every week on Tuesday at 8:00
->monthly(); Run the task every month
->monthlyOn(4, ’15:00′); Run the task every month on the 4th at 15:00
->quarterly(); Run the task every quarter
->yearly(); Run the task every year
->timezone(‘America/New_York’); Set the timezone

 Now schedule this command via CronJob.

Step 4: Scheduling the Commands.

Let’s schedule a task for running the command we just built.

According to its usage, our task is supposed to be run once a day. So we can use the daily() method. So we need to write the following code in the app  >>  Console  >>  Kerne.php file.

We will write the code inside the schedule function. Please refer to the documentation if you want more info about task scheduling,

// Kernel.php

   /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
          $schedule->command('registered:users')
                   ->everyMinute();
    }

You only need to add the following Cron entry to your server when using the scheduler.

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

In the localhost, I will hit the following command to get users’ mail.

php artisan schedule:run

After a minute, we see we are getting mail containing registered users. You can see more time intervals here. So this is how you can configure the cronjob in Laravel. 

You can find more about Task Scheduling in Laravel Documentation.

That’s it!

16 thoughts on “Laravel Cron Jobs Scheduling To Make Automation Easier”

  1. Hi, congratulations about post. Was useful to me.

    I have a doubt:

    According with the your cron created here, it will be executed every minute. In this case, how the Laravel know if a daily task already executed? It hold a historic after first time?

    Tks!!!

    Reply
  2. hello
    I am moaz amin I am new in laravel so i need some help in task scheduling. Your tutorial is very good but I have some questions.
    I am developing some task scheduling application in laravel.
    My question is that how to show a simple prompt box or simple alert box after every 1 minute or after any specified time using Task Scheduling. and how to open a web page using after 1 minute and etc.
    how to echo some text after some time continuously …. I can log the message after every minute but I am unable to show the echo please help me…

    following is my scheduled code
    $schedule->call(‘App\Http\Controllers\AdminController@showCron’)->everyMinute();

    and this is my controller method code
    public function showCron()
    {

    \Log::info(‘Controller Scheduled’);
    }

    after every minute this message entry inserted to log file But following code is nothing do

    public function showCron()
    {

    echo ‘Hello Scheduled’;
    }

    Reply
    • Where exactly you expect the message “Hello Scheduled” will be shown? Cron jobs run on background, so it probably works, but you can’t see the result of your command.

      Reply
  3. Expected response code 250 but got code “530”, with message “530-5.5.1 Authentication Required …I am getting this error how i can handle it

    Reply
  4. Hi , I tried all these works in localhost and every thing was ok but when i transfer files to live server i have received emails( every minute) ” Class ‘Illuminate\Console\Command’ ” . In my code , it should add records to a database table by each minutes . i created cron.php by artisan and in this file after namespace , Illuminate\Console\Command; is wrote . i am sure that all classes are present in its related folder but my work fail as above and no data become add to table. any idea is appreciated

    Reply
  5. HI, I saw your article this is good, but can you please suggest me how to set cron job, since I’ve windows os. Also in step 5 you’ve added this command:
    * * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
    which I assume is for cron job.

    Reply
  6. hello. I need send multiple emails with time, for example, send to one email after one minutes other and so on

    Reply
  7. I got this error help please

    C:\xampp\htdocs\crontutorial>php artisan registered:users

    Swift_TransportException : Expected response code 250 but got code “530”, with message “530 5.7.1 Authentication required

    at C:\xampp\htdocs\crontutorial\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\AbstractSmtpTransport.php: 457
    453: $this->eventDispatcher->dispatchEvent($evt, ‘responseReceived’);
    454: }
    455:
    456: if (!$valid) {
    457: $this->throwException(new Swift_TransportException(‘Expected response code ‘.implode(‘/’, $wanted).’ but got code “‘.$code.'”, with message “‘.$response.'”‘, $code));
    458: }
    459: }
    460:
    461: /** Get an entire multi-line response using its sequence number */
    462: protected function getFullResponse($seq)

    Exception trace:

    1 Swift_Transport_AbstractSmtpTransport::assertResponseCode(“530 5.7.1 Authentication required
    “)
    C:\xampp\htdocs\crontutorial\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\AbstractSmtpTransport.php : 341

    2 Swift_Transport_AbstractSmtpTransport::executeCommand(“MAIL FROM:
    “, [])
    C:\xampp\htdocs\crontutorial\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\EsmtpTransport.php : 305

    Please use the argument -v to see more details.

    Reply
  8. Hello Krunal Post was Awesome.
    I have one question below command

    php artisan schedule:run
    we have to run this command or it will automatically run after one minute ??

    Thanks

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.