Activate scheduled command task in laravel 11

Updated: Feb 22, 2025

Activate scheduled command task in laravel 11

To activate a scheduled command task in Laravel 11, you need to follow these steps:

  1. Define the command: First, you need to define a command class that you want to schedule. Laravel uses the Artisan command bus to handle commands. To create a new command, you can use the make:command Artisan command:
php artisan make:command MyCommand

Replace MyCommand with the name of your command class. This will create a new file in the app/Console/Commands directory.

  1. Write the command logic: Open the newly created command file and write the logic for your command. For example, you can define a handle method that contains the code you want to run when the command is executed:
namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mycommand {--force : Run the command forcefully}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'My custom command';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // Your command logic here
        $this->info('Command executed successfully.');
    }
}
  1. Schedule the command: To schedule the command to run at a specific time, you need to add it to the App\Console\Kernel file. Open the App\Console\Kernel.php file and add the schedule method call to the boot method:
protected function schedule(Schedule $schedule)
{
    $schedule->command('mycommand')
             ->daily(); // or hourly(), everyMinute(), everyFiveMinutes(), etc.
}

Replace mycommand with the name of your command. You can also specify the frequency of the command execution using the available methods like daily(), hourly(), everyMinute(), etc.

  1. Run the scheduler: To start the scheduler, you need to run the artisan schedule:work command in the terminal:
php artisan schedule:work

This command will start the Laravel scheduler and run any scheduled commands according to their schedule.

  1. Stop the scheduler: To stop the scheduler, you can use the Ctrl+C keyboard shortcut in the terminal where the artisan schedule:work command is running.

That's it! Your scheduled command task is now activated in Laravel 11.