How to use Cron Jobs with Laravel?
What is Cronjob :
A Cronjob is Unix command for scheduling jobs to be executed in specific time and specific interval. In Laravel development, cron jobs are often used to automate recurring tasks or to schedule specific actions within a Laravel application. Laravel provides a convenient way to define and manage these scheduled tasks using its built-in task scheduler, which is powered by cron jobs in the background. For example we can schedule a task in the server that executes some scripts that sends out daily/weekly reports from our website. Mainly we are using the cron jobs to cleanup the databases, send the emails , execute time consuming tasks ….etc. If i want to delete some files from my database which is older than a month, I can simply do that using Cron Job. Cron job will not work with with windows based machines or servers as it will only work on unix based machines.
Cron has a configuration file called Crontable also known as Crontab which is used to manage the scheduling.These crontab consists of different Cronjobs and each CronJob is associated with a specific task. Cron Job mainly consists of two parts, a Cron expression and a shell command to be run.
The format of the Cron Scheduler is like this
* * * * * command/to /run
ie, minute, hour, day, month, day of the weak in the place of * in the same order.
where :
- Minute (0-59)
- Hour (0-23)
- Day of month (1-31)
- Month (1-12)
- Day of the week (0-6 starting on Sunday-0)
When any entity is replaced with asterisk then the CronJob have to perform for each minute or day or weak or month or day of the weak according to where asterisk is placed.
CronJob Samples :
- Every hour on the 5th minute of the hour.
5 * * * * command-to – run
- Every hour on the 5th minute of the hour on mondays only.
5 * * * 1 command-to- run
- You can also run the cron job at an interval of time, let’s say every 10 minutes. For that you need to give this format (asterisk divide by number):
*/10 * * * * command- to – run
Task Scheduling in laravel:
Normally for scheduling tasks/ cronjobs you must SSH into your server to add the Cron entries. The command scheduler feature in Laravel allows you to easily and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server for running the laravel task scheduler in each minute.
Laravel’s task schedule is defined in the schedule method inside the
app/Console/Kernel.php file. We can define as much as tasks inside this method. Following is the only Cron entry you need to add to your server, which will call the Laravel command scheduler every minute.
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
This cronjob will initiate laravel task scheduler to run the tasks inside the schedule method.
Command Scheduling in Laravel :
To schedule the commands we use the Laravel task scheduler. The tasks were defined inside the schedule method of the kernel class. By using the command method we can add as many artisan commands we want. By using the schedule method we can schedule all the commands. There are different schedule frequencies we can apply on the commands according to the need. Some examples are listed here below.
— If one task is supposed to run once a day , then we can use the daily() method.
Protected function schedule(Schedule $schedule) { $schedule->command(‘sms:gudmorning’)->daily(); } -- If we want to run task every hour every day. $schedule->command(‘Task’) ->hourly();
— If we want to run task every day at 10.30.
$schedule->command(‘Task’) ->dailyAt(‘10.30’);
— If we want to run a task every week.
$schedule->command(‘Task’) ->weekly( );
— If we want to run it every month.
$schedule->command(‘Task’) ->monthly( );
— It also provides some schedule constraints. If we want we can combine the above methods to perform some action.
$schedule->command(‘Task’) ->weekly( ); ->mondays(); ->at(10.30);
Scheduling Closure calls :
If we want to schedule a Closure to be called every day at midnight and within the Closure we will execute a database query to clear a table
protected function schedule(Schedule $schedule) { $schedule->call(function () { DB::table('recent_users')->delete(); })->daily(); }
Scheduling exec commands :
we can use the exec command to issue a command to the operating system.
$schedule->exec('node /home/forge/script.js')->daily();
Schedule Options available in Laravel :
The different type of schedules we can assign to our tasks are,
->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
->everyThirtyMinutes(); — Run the task every thirty minutes
->hourly(); — Run the task every 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
->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
->when(Closure); — Limit the task based on a truth test
Conclusion:
Introduction of Laravel Task scheduler made the cronjob setup easier without SSH into your server to add the Cron entries. The Laravel command scheduler helps us to expressively define the command schedule within Laravel and only a single Cron entry is needed on your server.
To schedule a Cron Job you can follow the post above.
Cheers !