Task scheduling with cron job in laravel

Last updated : Dec 12, 2021

Task scheduling with cron job in laravel



In this article you will get to know about task scheduling with cron job in Laravel in Linux.

Sometimes you need some tasks in your system to run without your consent or without anyone's interruption. That's when task scheduling comes into the picture.
There are few tasks which has to be done at certain point of time without programmer's intervention. For eg.

  1. wishing someone's birth anniversary, marriage anniversary

  2. deleting unused files at every day at 12pm

  3. in financial system giving payout to a user at any time of day/month/year

According to Techopedia.com Job scheduling is the process of allocating system resources to many different tasks by an operating system (OS). The system handles prioritized job queues that are awaiting CPU time and it should determine which job to be taken from which queue and the amount of time to be allocated for the job. This type of scheduling makes sure that all jobs are carried out fairly and on time.

Let's see how to create a task scheduler in Laravel in Linux first and then in Windows. So what we are doing here is we will create a command and then add it in kernel file and then add it in crontab(in Linux) and task scheduler(in Windows) to link Laravel command with operating system's job batch. And we will program the command to run every minute and when the task will run it will some data to a database table.

After this theory, let's see how to create task scheduling with cron job in Laravel in Linux OS

  1. First open up your terminal/command prompt with administrative privileges. And type in the command

    laravel new cronjob
  2. Then change directory by typing

    cd cronjob
  3. now create command by typing

    php artisan make:command CronTab
    . After command you will get a new directory named Commandsin app/Console. And in the same directory you will also get file named CronTab.php which you just created.
  4. Now click on that file and type in script

    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use App\SysNotification;
    
    class CronTab extends Command
    {
        
        protected $signature = 'cron:tab';
    
        
        protected $description = 'Command description';
    
        
        public function __construct()
        {
            parent::__construct();
        }
    
        
        public function handle()
        {
            \Log::info("cron worked");
            $new_not = new SysNotification;
            $new_not->data = "dummy data";
            $new_not->save();
    
            $this->info('ran successfully');
        }
    }
  5. Now its time to add this command in Laravel app's kernel file. For this open app/Console/Kernel.php file and type in the script.

    <?php
    
    namespace App\Console;
    
    use Illuminate\Console\Scheduling\Schedule;
    use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
    
    class Kernel extends ConsoleKernel
    {
        
        protected $commands = [
            Commands\CronTab::class
        ];
    
        
        protected function schedule(Schedule $schedule)
        {
            $schedule->command('cron:tab')->everyMinute();
        }
    
        
        protected function commands()
        {
            $this->load(__DIR__.'/Commands');
    
            require base_path('routes/console.php');
        }
    }
  6. Now it's time to create a model for a database table so that when the task will run it will add a row in database table. Switch to terminal and type

    php artisan make:model SysNotification

  7. Also create a migration for the model. Switch to terminal and type

    php artisan make:migration sys_notifications

  8. Now go to database/migrations and open newly created file. type in the script.

    <?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateSysNotificationsTable extends Migration
    {
        
        public function up()
        {
            Schema::create('sys_notifications', function (Blueprint $table) {
                $table->id();
                $table->string('data',50);
                $table->timestamps();
            });
        }
    
        
        public function down()
        {
            Schema::dropIfExists('sys_notifications');
        }
    }

  9. Now migrate the database. Go to terminal/command prompt enter into your app's directory and type

    php artisan migrate:fresh

  10. Now its time to check the command which we have created. Go to terminal/command prompt enter into your app's directory and type

    php artisan cron:tab
    Now if you check in phpmyadmin or whatever software you have to manage database, you will see a new row in sys_notifications table. .

The scheduler task scripting is complete in the app. But till now the work is not complete because the task is not linked with OS's job batch.

  1. So let's start linking for Linux. Open up terminal and type

    crontab -e
    and select whichever editor you are good at. Type
    * * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

  2. This was it for this article. We will continue bringing interesting articles related to programming.




Sign in for comment. Sign in