skip to Main Content

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


  1. Create a function to perform the job you want and call it recursively in you controller.

    function schedule($input,$delay_time = 60 ){
    // Whatever you want to do with $input here.
    sleep($delay_time);
    schedule($delay_time);
    }
    
    schedule($_GET['request']);
    

    This function will run each 60 second. Hope i have got what you want. English is my second language.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search