Hello Geek, In Laravel, you can easily schedule recurring tasks using a feature called “Task Scheduling”. Task Scheduling is built on top of the underlying Unix cron job scheduling system, but provides a more expressive syntax for defining schedules.
Here are the steps to create a Cron Job in Laravel:
Step 1: Create a Command
The first step is to create a Laravel command that defines the task you want to run. You can do this by running the following command in your terminal:
php artisan make:command MyCommand
This will create a new file called ‘MyCommand.php
‘ in the ‘app/Console/Commands
directory‘.
In the ‘handle()
‘ method of your command class, you can define the logic for the task you want to run. For example, let’s say you want to send a daily email to all users. You could define the logic for this task in the ‘handle()
‘ method like so:
public function handle()
{
$users = User::all();
foreach ($users as $user) {
Mail::to($user)->send(new DailyEmail());
}
}
Step 2: Define a Schedule
Next, you need to define a schedule for your command. You can do this in the ‘schedule()
‘ method of the ‘App\Console\Kernel
‘ class. This class is located in the ‘app/Console
‘ directory.
In the ‘schedule()
‘ method, you can use the ‘->command()
‘ method to schedule your command. For example, to schedule the ‘MyCommand
‘command to run every day at midnight, you would use the following syntax:
protected function schedule(Schedule $schedule)
{
$schedule->command('mycommand')->dailyAt('00:00');
}
This will run the ‘MyCommand
‘command every day at midnight.
Step 3: Configure the Cron Job
Finally, you need to configure the actual cron job on your server. You can do this by adding an entry to your server’s crontab file.
Open your server’s crontab file by running the following command:
crontab -e
This will open the crontab file in your default editor. Add the following line to the end of the file:
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
This will run the Laravel scheduler every minute. The scheduler will check whether any tasks need to be run at that time, and will execute them if necessary.
And that’s it! Your Laravel cron job is now set up and running. You can add as many tasks as you like to the schedule()
method of the Kernel
class, and they will all be run according to their schedule.
All the best nerd!