First, we should know what is a cron job?
Cron is a Linux tool, which schedules a command or script on the server to run automatically at a specific time interval. That means no event is needed to run the cron page.
Laravel gives us a simple and easy process to activate cron in our project. If you follow the below step, you can set the cron in your project.
Step 1: Go to your command prompt where your project is kept. Now paste the below command
php artisan make command: yourCronName
after running this command, a new file created in app/Console/Command/yourCronName.php
Step 2: open the yourCronName.php page and write your code(suppose send email) within handle() function.
class yourCronName extends Command
{
use TenantConnector;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = ‘notify:myCronNotification‘;
// notify:myCronNotification is used as a command when you schedule the cron
/**
* The console command description.
*
* @var string
*/
protected $description = ‘Cron Notification’;
Public function handle(){
// write your code
}
protected $signature = ‘notify:emailforpushnotification’;
You can add a model in this page using use keyword under a namespace, so you can access your database here.
Step 3: Go to app/Console/Kernel.php page and register you cron command
protected $commands = [
// register your command
commands\yourCronName
];
Now, when you want to execute the cron, please set the schedule time
protected function schedule(Schedule $schedule)
{
$schedule->command(‘notify:myCronNotification’)
->everyMinute();
}
Your cron is now set and it fires in your given time of interval.
Laravel provides a wide range of schedule frequency options
Method |
Description |
---|---|
|
Run the task on a custom Cron schedule |
|
Run the task every minute |
|
Run the task every five minutes |
|
Run the task every ten minutes |
|
Run the task every fifteen minutes |
|
Run the task every thirty minutes |
|
Run the task every hour |
|
Run the task every hour at 17 mins past the hour |
|
Run the task every day at midnight |
|
Run the task every day at 13:00 |
|
Run the task daily at 1:00 & 13:00 |
|
Run the task every week |
|
Run the task every week on Monday at 8:00 |
|
Run the task every month |
|
Run the task every month on the 4th at 15:00 |
|
Run the task every quarter |
|
Run the task every year |
|
Set the timezone |
Senior Software Engineer at Openweb Solutions