PASSWORD RESET

Your destination for complete Tech news

How to schedule a task in Laravel?

273 0
< 1 min read

In Laravel, you can schedule tasks to be run at specific intervals using the task scheduler. To use the task scheduler, you will need to define your tasks in the app/Console/Kernel.php file and set up a Cron entry on your server to run the schedule:run Artisan command.

Here’s an example of how you can schedule a task in Laravel:

  1. In the app/Console/Kernel.php file, define your task in the schedule method. This method receives an instance of the Illuminate\Console\Scheduling\Schedule class, which you can use to define your task.

For example, to schedule a task that sends an email every day at 8:00 AM, you can do the following:

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        Mail::to('[email protected]')->send(new DailyReport());
    })->dailyAt('8:00');
}

To run the task scheduler in Laravel, you will need to set up a Cron entry on your server to run the schedule:run Artisan command.

1. Open your server’s Cron file by running the following command:

crontab -e

2. Add the following entry to the Cron file to run the schedule:run command every minute:

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

Replace /path/to/artisan with the path to the artisan file in your Laravel installation.

3. Save the Cron file and exit.

The task scheduler will now run the schedule:run command every minute, and any tasks that are scheduled to run will be executed.

It’s also worth noting that you can run the task scheduler manually by running the php artisan schedule:run command from the command line. This can be useful for testing or debugging your scheduled tasks.

Leave A Reply

Your email address will not be published.

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