How to execute a function in cron job?

0

I would like to know how and how best to perform a cron job, if I write it as a direct function in cron? I would like to do it every day at 6am.

public function atualizarpontuacao(){
       $palpites = Listadepalpites::all();
       $data = date('Y-m-d');
       $data1 = date('Y-m-d', strtotime($data. ' -3 days'));
         foreach($palpites as $p){
           $palpitea = $p->palpitea;
           $palpiteb = $p->palpiteb;
           $id       =  $p->id;
           $id_c     = $p->id_c;
           $id_u     = $p->id_u;
          $confrontos = Listadejogos::Find($id_c);
           $scorea   = $confrontos->scoretimea;
           $scoreb   =  $confrontos->scoretimeb;
           $pontuacao =3;

           DB::update("update palpite set pontuacao='$pontuacao' where (id='$id' and diadojogo > '$data1') ");

         }
    
asked by anonymous 07.10.2017 / 01:00

1 answer

0

Since you are using Laravel, you can write this function into the protected function schedule(Schedule $schedule) method of the App\Console\Kernel class.

The example of what your function would look like follows:

protected function schedule(Schedule $schedule) {
    $schedule->call(function () {

       $palpites = Listadepalpites::all();
       $data = date('Y-m-d');
       $data1 = date('Y-m-d', strtotime($data. ' -3 days'));

       // Código segue...

    })->dailyAt('06:00');
}

For your code to enter cronjob, you also need to put the following line in your cronjob:

* * * * * php /caminho-para-o-projeto/artisan schedule:run >> /dev/null 2>&1

EDIT

You can also use Command classes to schedule jobs (particularly, you can better reuse your code that way). Here is an example:

  • Open the CMD in the folder of your project and type php artisan make:command AtualizaPontuacao .

  • Laravel will generate a file named AtualizaPontuacao.php within app\Console\Commands . Inside it, there will be an attribute called protected $signature . In this attribute, you will tell the signature of your command. For example: atualiza:pontuacao .

  • Within the public function handle() method, you can write all your code.

  • For your command to work, return to the App\Console\Kernel class and add the name of your Command class to the protected $commands = [ ... ] attribute: App\Console\Command\AtualizaPontuacao::class

  • Now, change the code that is within the protected function schedule(Schedule $schedule) method for the example below:

    $schedule->command('atualiza:pontuacao')->dailyAt('06:00');

  • Ready! Now, your code will run both in cronjob and manually as well, using the command php artisan atualiza:pontuacao .

  • For more timestamp and date settings for cronjob and commands, go to the Laravel documentation:

    CronJobs: link

    Artisan Commands: link

        
    07.10.2017 / 01:58