ottaviane's avatar

croning a route

Hi all, I need to "cronify" a route... every day my systema must execute this:

Route::post('/getInfoPrefUser', 'scadenziarioController@getInfoPrefUser');
of my web.php

So I'm following the method described in "Task scheduling" section of Laravel guide but I don't find how to invoke a route. Can you help me please?

0 likes
8 replies
Ricus's avatar

Why not just create a scheduled task that calls the function that the mentioned route would call?

For instance the getInfoPrefUserfunction does some sort of logic, and all you need to do is call this same logic from your scheduled command

1 like
ottaviane's avatar

Ok, thank you.... so I have to do simply this:

in my kernel.php 

....
use App\Http\Controllers\scadenziarioController;
....

and

protected function schedule(Schedule $schedule)
    {
        scadenziarioController::getInfoPrefUser();
    }

is it correct?

Ricus's avatar
Ricus
Best Answer
Level 3

@ottaviane that doesn't look correct

There is a few approaches but the easiest is probably to go to your Kernel class (The one that extend the ConsoleKernel located at app/Console/Kernel.php)

Inside this class there is a function called schedule where you can add all your scheduled commands (https://laravel.com/docs/7.x/scheduling#scheduling-artisan-commands)

$schedule->call(function () {
          (new scadenziarioController)->getInfoPrefUser()
})->daily();

Another solution would be to create a new artisan command which performs the logic you need, and call that artisan command in your scheduler.

With an artisan command, you would have the following in your schedule method:

$schedule->command('user:get-info')->daily(); // or whatever signature you gave the command

Keep in mind both of these suggestions will only work if you have set up a cron entry to call php artisan schedule:run every minute. This is all lined out in the link I sent above

1 like
ottaviane's avatar

or is better this?

protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            scadenziarioController::getInfoPrefUser();
        })->everyMinute()
          ->withoutOverlapping();        
    }
Ricus's avatar

@ottaviane see my previous reply.

This command would run every minute, but you indicated you want it to only run once a day, so then you would use daily() instead of everyMinute()

1 like
ottaviane's avatar

ok. thank you very very mutch. You were very helpfull. this is my crontab:

#laravel cronjob
* * * * * cd /var/www/html/scadenziario && php artisan schedule:run >> /dev/null 2>&1

bye.

Ricus's avatar

@ottaviane no problems, please do mark one of my answers as the correct / best answer to your initial question so other users can find it easily and know that the issue has been resolved

Please or to participate in this conversation.