×


Creating a Cron job in Laravel 5.2 :Task Scheduling

To create a cron job in Laravel 5.2 ,move to the app/console/ folder.The console folder contains all the relevant configuration files and folders for you to create a custom artisan command in Laravel 5.6 .  After creating the custom artisan command ,we can schedule the command to be run in specific intervals

Step 1

Run

 

to create new custom artisan command,This will generate a class called app/Console/Commands/CronJob.php.The newly generated file will have the following structure.You have to fill in name and description variables in the file.You can use the DB and MODEL files from CronJob.php. The file extends the Command Class

 

app/Console/Commands/CronJob.php

Here we select a set of users based on some custom criteria from the users table and do something to them periodically with the cron job.The action for the should be written in the CronJob.php – handle() function.The class defines our command.To run this need to use the following

php artisan cronjob

Step 2

Scheduling the job

To schedule the when to run the command we have created open the kernel.php file in the app/console/ folder

app/console/kernel.php

The kernel class extends ConsoleKernel .To add the commands

and to schedule the command

 

This runs the command at every monday at 8:00

Step 3

Running the scheduler

To start the scheduler that checks for   the scheduled tasks every minute,use the following command in terminal

This is a simplified version of the scheduler.To see more options provided by the Laravel scheduler , see the below official documentation

https://laravel.com/docs/5.6/scheduling

No Comments

Leave a Reply

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