PASSWORD RESET

Your destination for complete Tech news

How to create a custom cron job in Laravel?

476 0
< 1 min read

In Laravel, you can create a custom cron job using the Artisan command make:command. This will generate a new class in the app/Console/Commands directory that extends the Illuminate\Console\Command class.

Here are the steps to create a custom cron job:

Run this command to generate a new command

php artisan make:command MyCustomCronJob

This will create a new file called MyCustomCronJob.php in the app/Console/Commands directory. Open this file and update the $signature property to define the name and arguments of your command. For example:

protected $signature = 'my:cronjob {--option}';

This defines a command named my:cronjob with an optional --option argument.

Update the handle() method to define the logic for your cron job. This method will be called when your command is run by the cron scheduler. For example:

public function handle()
{
    $option = $this->option('option');
    
    // Your cron job logic here
}

This example retrieves the value of the --option argument and executes some custom logic.

Register your command in the app/Console/Kernel.php file. Add your command to the $commands array in the protected $commands property. For example:

protected $commands = [
    Commands\MyCustomCronJob::class,
];

Schedule your custom cron job in the app/Console/Kernel.php file. Add a new entry to the $schedule property in the schedule() method. For example:

protected function schedule(Schedule $schedule)
{
    $schedule->command('my:cronjob')->everyMinute();
}

This schedules your custom cron job to run every minute. Replace everyMinute() with any other available scheduling option as per your requirement.

That’s it! Your custom cron job is now registered and scheduled to run at the specified interval. You can test it by running the php artisan schedule:run command in your terminal.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.