NAMAssist
NAMAssist

Reputation: 381

Laravel - Send custom parameter to scheduled tasks (commands)

Currently I have 4 different commands in "app/Console/Commands/", and I set them all up in app/Kernel.php, like this:

$schedule->command('command:start-imports-group-a')->everyFiveMinutes()->runInBackground()->withoutOverlapping();
$schedule->command('command:start-imports-group-b')->everyFiveMinutes()->runInBackground()->withoutOverlapping();    
$schedule->command('command:start-imports-group-c')->everyFiveMinutes()->runInBackground()->withoutOverlapping();    
$schedule->command('command:start-imports-group-d')->everyFiveMinutes()->runInBackground()->withoutOverlapping();

In my command php files (e.g. StartImportsGroupA.php, StartImportsGroupB.php, etc.) they are all calling the same function, but I'm simply setting a variable in each to change the "group" value. For example:

StartImportsGroupA.php

public function handle()
{
     $group = 'a';
     $this->startImports($group);
}

StartImportsGroupB.php

public function handle()
{
     $group = 'b';
     $this->startImports($group);
}

...and so on.

Is there an better way to do this? E.g. pass the "group" parameter to the command? That way I won't need 4 different command files to simply change that one $group variable's value.

Upvotes: 3

Views: 4742

Answers (2)

NAMAssist
NAMAssist

Reputation: 381

Thanks SpinyMan, although I had to do some more research for the remainder of the answer. The full answer is this:

  1. Set the arguments (you can pass options also) in the $signature
  2. Specify an array as the second value of $schedule->command(), each value is in order, containing the value to be passed. Since {group} is mentioned first in the $signature, that value should be the first value in the array passed to $schedule->command()
  3. Retrieve the argument (or option) value in handle() as needed

Working Example:

In app/Console/Commands/StartImports.php file:

protected $signature = 'command:start-imports {group}';

public function handle()
{
        $group = $this->argument('group');
}

In app/Console/Kernel.php file:

$schedule->command('command:start-imports', ['a'])->everyFiveMinutes()->runInBackground()->withoutOverlapping();
$schedule->command('command:start-imports', ['b'])->everyFiveMinutes()->runInBackground()->withoutOverlapping();
$schedule->command('command:start-imports', ['c'])->everyFiveMinutes()->runInBackground()->withoutOverlapping();
$schedule->command('command:start-imports', ['d'])->everyFiveMinutes()->runInBackground()->withoutOverlapping();

I hope this helps anyone else who needs this!

Upvotes: 2

SpinyMan
SpinyMan

Reputation: 484

You can use second parameter as array of options for your command:

$schedule->command(StartImportsGroupCommand::class, ['--group=a'])
    ->everyFiveMinutes()
    ->runInBackground()
    ->withoutOverlapping();

Do not forget to describe this option --group in command code.

Upvotes: 5

Related Questions