How do I schedule tasks with Laravel Scheduler?

Laravel Scheduler is a powerful task scheduling tool built into the Laravel framework. It allows developers to schedule periodic tasks directly within the application using a clean and expressive syntax. This feature is especially useful for scheduled jobs like database cleanup, sending emails, generating reports, and more.

How to Use Laravel Scheduler

To schedule tasks using Laravel Scheduler, you'll typically define your scheduled commands in the app/Console/Kernel.php file. The schedule method is where you'll set up your command schedule.

Example of a Scheduled Task

protected function schedule(Schedule $schedule) { // Schedule an email to be sent every day at midnight $schedule->call(function () { // Logic to send email })->daily(); // Schedule a command to run every hour $schedule->command('inspire')->hourly(); // Schedule a job to run every Monday at 9 AM $schedule->job(new MyJob())->weeklyOn(1, '9:00'); }

After defining your scheduled tasks, you need to set up a cron entry on your server that calls the Laravel command scheduler every minute. You can do this by editing your crontab:

crontab -e

Add the following line:

* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

Conclusion

Laravel Scheduler provides a simple and effective way to manage scheduled tasks within your application. By defining your tasks in one central place and using cron to trigger them, you can keep your application's processes running smoothly.


Laravel Scheduler Task Scheduling Laravel Console Cron Jobs