Laravel Cron Job – Task Scheduling Setup Example

In this laravel cronjob tutorial, We would like to share with you how to create cronjob and how to test cronjob in localhost. We will also discuss how to set cronjob on live server. And this example also work with laravel 5.8 version.

Generally laravel cronjob is task scheding. it means it will work according scheduled time. If you want to schedule tasks that will be executed every day automatically that is very helpful for you. Laravel cronjob is reduce the manually working time.

Content

  • Create Command Class
  • Implement Logic
  • Register Command
  • Test in Localhost
  • Laravel Set CronJob Live Server
  • Conclusion

Create Command Class

Go to your project root directory using the below command :

cd your project name 

Next, We need to create command class run by below command in command prompt :

php artisan make:command TodayUsers

Implement Logic

After run this above command, it will create a new class name TodayUsers.php in app/Console/Commands/ folder. So go to app/Console/Commands/TodayUsers.php and implement your logic here :

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This laravel cronjob is used to check how many users registered today';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
            $count = \DB::table('users')
            ->whereDate('created_at', '=', date('Y-m-d'))
            ->count();

            echo "Today $count users registered";
    }
}

Register Command

After successfully implement your logic in TodayUsers.php file, we need to register this command in kernel.php file with task scheduling :

lets open app/Console/Kernel.php/ and schedule the task.

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

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

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

        require base_path('routes/console.php');
    }
}

In Kernel.php file we will schedule the task to be done, when it will be the command excute(run).
In this example we will schedule the task excute for every minute. But you can schedule accordingly.

Test in Localhost

After scheduling the task, we will excute this above in localhost for testing.

let go to command prompt and run the below command :

php artisan TodayUsers:check

Laravel Set CronJob on live server

If you want to schedule the task on live server use the below command :

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

Conclusion

In this laravel cronjob tutorial, we have successfully test created cronjob and we have also learned how to set cronjob on live server .

In Laravel More Cronjob Schedule Options are available. If you want to know more click here

->cron(‘* * * * * *’); – Run the task on a custom Cron schedule

->everyMinute(); – Run the task every minute

->everyFiveMinutes(); – Run the task every five minutes

->hourly(); – Run the task every hour

->daily(); – Run the task every day at midnight

->dailyAt(’13:00′); – Run the task every day at midnight

->twiceDaily(1, 13); – Run the task daily at 1:00 & 13:00

->weekly(); – Run the task weekly

->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 Addiitional schedule constraints are listed below,

->weekdays(); – Limit the task to weekdays

->sundays(); – Limit the task to Sunday

->mondays(); – Limit the task to Monday

->tuesdays(); – Limit the task to Tuesday

->wednesdays(); – Limit the task to Wednesday

->thursdays(); – Limit the task to Thursday

->fridays(); – Limit the task to Friday

->saturdays(); – Limit the task to Saturday

Recommended Laravel Tutorial

  1. Laravel Tutorial From Scratch | Step By Step
  2. Laravel 6 Ajax CRUD(DataTables Js) Tutorial Example
  3. Laravel 6 – Ajax CRUD (Operation) Application Example
  4. Laravel 6 Angular JS CRUD Example Tutorial
  5. Upload Files/Images to Amazon s3 Cloud Using Laravel 6 Filesystem
  6. Laravel 6 CKEditor with Image Upload
  7. Ajax Image Upload In Laravel Tutorial Example From Scratch
  8. Laravel 6 Intervention Upload Image Using Ajax – Example
  9. Laravel Upload Image to Database with Validation
  10. Send Email Example Laravel
  11. Generate OR Create PDF In Laravel 6 Example
  12. Simple Generator or Create Qr Code Example Laravel
  13. Laravel Custom Cron Schedule Example Tutorial
  14. Laravel 6 Github Login Example

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

2 replies to Laravel Cron Job – Task Scheduling Setup Example

  1. i’m developer from Nigeria.. tnx a lot

  2. Well done

Leave a Reply

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