AppDividend
Latest Code Tutorials

Laravel Cronjob Scheduling Tutorial

4 2,630

Get real time updates directly on you device, subscribe now.

Laravel Cronjob Scheduling Tutorial is the topic, we will discuss in brief. In any web application, we need specific administrative tasks that run periodically and doing that manually is not a good idea. Whether you want to send out emails to your customers on particular events or clean up the database tables at the specific time, you will need a task scheduling mechanism to take care of the tasks. Cron is a task scheduler in UNIX-like systems, which runs shell commands at specified intervals.

If we want to schedule tasks that will be executed every so 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 which runs scheduled tasks at specific intervals. Cron uses the configuration file called crontab, also known as cron table, to manage the scheduling process. Crontab contains cron jobs, each related to a specific task. Cron jobs 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 a command using Laravel Console and then schedule that command at a particular time. When using the scheduler, you only need to add the following Cron entry to your server.

Laravel Cronjob Scheduling Tutorial

First, we download the fresh laravel and then start working on the example.

Step 1: Configuring the Laravel.

Type the following to generate boilerplate of Laravel 5.6.

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

Okay, 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=

Now, migrate the tables into the database.

php artisan migrate

Step 2: Create User Authentication.

Laravel provides Authentication system out of the box. Just hit the following command.

php artisan make:auth

It will generate authentication scaffolding.

Next step, start the Laravel development server using the following command.

php artisan serve

Go to this URL: http://localhost:8000/register

Register one user.

Step 3: Create Laravel Artisan Command.

If you are new to Laravel Console, then please check out my Laravel Artisan Console Tutorial. We use the make: console Artisan command to generate a command class skeleton to work with. In this application, we will just send one email to the owner telling that, we have these number of users registered today. So type the following command to generate our console command.

Related Posts
1 of 34
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. Now, we need to register this command inside 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 to call in via CronJob and get the job done. Now, 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 4: Create a mailable class to send the mail.

Type following command to generate mail class.

php artisan make:mail SendMailable

So, 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 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');
    }
}

Also, define the view for this mail at resources  >>  views  >> emails  >>  registeredcount.blade.php file. The mails folder is not there, so need to create one and then add the view registeredcount.blade.php.

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

Now, add this mailable class inside 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 a mail, I have used Mailtrap. You can quickly signup there. It is free for some usage. It fakes the email, so it is convenient to test our application.

Now, type the following command to execute our code. Let us see that if we can get the mail.

php artisan registered:users

Zoinks, we are getting the email that is saying that a Total number of registered users for today is: 1. Now schedule this command via CronJob.

Step 5: Scheduling the Commands.

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

Our task, according to its usage, is supposed to be run once a day. So we can use the daily() method. So we need to write following code in the app  >>  Console  >>  Kerne.php file. We will write the code inside schedule function. If you want to more info about task scheduling, then please refer the documentation.

// 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();
    }

When using the scheduler, you only need to add the following Cron entry to your server.

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

For me in localhost, I will hit the following command to get the mail of users.

php artisan schedule:run

After a minute, we can see that we are getting one mail that contains some users registered today. You can see more time interval here.  So this is how you can configure the cron job in Laravel. Finally, our Laravel Cronjob Scheduling Tutorial is over. Thanks for taking. Good Bye.

4 Comments
  1. Carlos Mora says

    Great article! Thanks!

  2. MCCI says

    Thanks so much 😀

  3. Leandro says

    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!!!

  4. Moaz Amin says

    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’;
    }

Leave A Reply

Your email address will not be published.