AppDividend
Latest Code Tutorials

Laravel Cronjob Scheduling | Task Scheduling In Laravel

15

Laravel Cronjob Scheduling Example is the topic. In any web application, we need specific administrative tasks that run periodically, and doing that manually is not a good idea. Applications require some tasks to be run periodically on the server.

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

To automate these tasks, a task scheduling system is required. Laravel Cron Job offers an elegant Task Scheduling or Laravel Cronjob Scheduling mechanism.

What is Cronjob?

Content Overview

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 that 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 Example

Whether you want to send out emails to your customers on 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.

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

Step 1: Configuring the Laravel.

Type the following to generate the boilerplate of Laravel 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 an 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 the Laravel Artisan Command.

If you are new to Laravel Console, then please check out my Laravel Artisan Console Example

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 these number of users registered today. So 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. Now, we need to 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 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 we 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 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 an 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 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 we 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. 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 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 the following code in the app  >>  Console  >>  Kerne.php file.

We will write the code inside the schedule function. If you want more info about task scheduling, then please refer to 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 the 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. 

You can find more about Task Scheduling in Laravel Documentation.

Finally, our Laravel Cronjob Scheduling | Task Scheduling In Laravel Example is over. Thanks for taking it. Good Bye.

Related Posts

Laravel Desktop Notification Implementation Example

Laravel Scout Algolia Search Example

How To Create Filters In Laravel

Laravel Firebase Example

Laravel guzzle http client Example

Laravel Datatables Example

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

    1. exidas says

      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.

  5. tarek says

    https://appdividend.com/2018/03/01/laravel-cronjob-scheduling-tutorial/
    i saw this link of yours , i did everything on local host , but where i run schedule run the terminal says i have no scheduled runs , i tried it on my website , still didn’t get it either , when i have did the “php artisan registered:users” it sends me an email straight away , can you please help or upload video to explain what is wrong or something

  6. himani says

    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

    1. Ting says

      mailtrap credential

  7. saman says

    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

  8. sagar kunjadiya says

    Can you tell me how can i set run task to 8 days interval

    1. Debanjan says

      ->cron(‘0 0 */8 * *’)

  9. Amit Kumar says

    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.

  10. Joshua says

    Getting ajax error trying to add this on bluehost

  11. Uzdeveloper says

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

  12. Bibek says

    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.

Leave A Reply

Your email address will not be published.

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