I would like to receive a GET Request in HelloController and execute a scheduled process (HelloWorldCommand) based on the content of request, but I am having trouble understanding how to do this.
PHP 8.2.7
Laravel Framework 10.25.0
In the following situation, GET request works and no error is output, but scheduling is not performed. What should I do?
HelloController.php
<?php
namespace AppHttpControllers;
use IlluminateSupportFacadesArtisan;
use AppConsoleCommandsHelloWorldCommand;
use IlluminateHttpRequest;
class HelloController extends Controller
{
//
public function index()
{
$output = '';
$variableValue = 'SampleValue';
Artisan::call('command:hello', ['variable' => $variableValue, '--quiet'=>true], $output);
var_dump($output);
return view('hello');
}
}
HelloWorldCommand.php
class HelloWorldCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:hello {variable}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
$v = $this->argument('variable');
//
$schedule = app(Schedule::class);
$schedule->call(function () {
logger("log {$v}");
})->everyMinute();
logger('test');
return 0;
}
}
I expected it to be written to the log file every minute, but the implementation was not processed on a scheduled basis.
2
Answers
Create a function to perform the job you want and call it recursively in you controller.
This function will run each 60 second. Hope i have got what you want. English is my second language.
The root problem of why it doesn’t work, is a mix of the fact that your crontab running the scheduler, will never be aware of your request context specific addition of a schedule and that your addition is only temporary, as the processed lines in
HelloWorldCommand::handle()
only exists till your request has finished.So basically, what you’re trying to do isn’t possible.
You should probably look into queuing jobs instead, which is something you could do to achieve a similar implementation.