Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Running php artisan migrate, triggers functions in cron scheduler

Tags:

php

cron

laravel

So I have an interface I called iCron

namespace App\Console\CronScripts;

interface iCron{
    public static function run($args);
}

I also have a class that uses this called UpdateStuff

class UpdateStuff implements iCron{

    public static function run($args = NULL){
        //I do api calls here to update my records
        echo "Begin Updating Stuff";
    }
}

So inside the Kernel I have:

use App\Console\CronScripts\UpdateStuff;

class Kernel extends ConsoleKernel{
    protected $commands = [];

    protected function schedule(Schedule $schedule){
        $schedule->call(UpdateStuff::run(NULL))->dailyAt('23:00');
    }
}

Which as it says I want to call the run function of UpdateStuff daily at 11PM. However the problem, is that it's calling the run function every time I use:

php artisan migrate

Anyone have any ideas why this is happening?

Thanks in advance!

EDIT: So I found where it's calling the schedule function,

 vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php

This calls the defineConsoleSchedule() function which in-turn runs $this->schedule($schedule); Then for some reason, UpdateStuff::run($args) is executing even though It's not 11PM

like image 881
Snowdrama Avatar asked Oct 30 '22 16:10

Snowdrama


1 Answers

I figured it out! So for anyone who is confused, the cron scheduler needs a Closure or a string that points to a static function with no parameters. Here's what I came up with:

class Kernel extends ConsoleKernel{
    protected $commands = [];

    protected function schedule(Schedule $schedule){
        //This calls the run function, but with no parameters
        $schedule->call("App\Console\CronScripts\UpdateStuff::run")->dailyAt('23:00');

        //If you need parameters you can use something like this 
        $schedule->call(function(){
            App\Console\CronScripts\UpdateStuff::run(['key' => 'value']);
        })->dailyAt('23:00');
    }
}

Hope This helps someone!

like image 132
Snowdrama Avatar answered Nov 07 '22 20:11

Snowdrama