DEV Community

Alexandre Freire
Alexandre Freire

Posted on

Como criar um cron no Laravel

Para criar CRON no laravel siga os seguintes passos:

1) Crie um command da seguinte forma:

php artisan make:command ExampleCron --command=example:cron 
Enter fullscreen mode Exit fullscreen mode

dentro desse arquivo que foi criado na pasta app/Console/Commands/ExampleCron.php.

namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
class ExampleCron extends Command
{

    protected $signature = 'example:cron';

    protected $description = 'Command E-mail';

    public function __construct()
    {
        parent::__construct();
    }
    // aqui você coloca a lógica do seu processo
    // pode utilizar todos os recursos do Laravel
    public function handle()
    {
        \DB::table('emails')->get(); // pega os e-mails
        // siga o código de sua preferencia
        // executando as funções de envio de e-mail
        $this->info('Example Cron comando rodando com êxito');
    }
}
Enter fullscreen mode Exit fullscreen mode

Altere as variáveis $signature e $description conforme exemplo e no método handle() a lógica do processo.

2) Para registrar esse command entre na pasta e arquivo app/Console/Kernel.php e abra o Kernel.php para adicionar no array do $commands adicione mais o command criado.

namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Inspire::class,
        Commands\ExampleCron::class,
    ];
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('inspire')->hourly();

        $schedule->command('example:cron')->daily(); // email diários
    }
}
Enter fullscreen mode Exit fullscreen mode

3) Agora adicione essa linha no seu arquivo cron

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1
Enter fullscreen mode Exit fullscreen mode

Pode ser configurado de várias formas e vários horário, exemplo quadro:

***Schedule Frequency Options***
*---------------------------------*-----------------------------------------------------*
| Method                          | Description                                         |
| ->cron('* * * * * *');          | Run the task on a custom Cron schedule              |
| ->everyMinute();                | Run the task every minute                           |
| ->everyFiveMinutes();           | Run the task every five minutes                     |
| ->everyTenMinutes();            | Run the task every ten minutes                      |
| ->everyFifteenMinutes();        | Run the task every fifteen minutes                  |
| ->everyThirtyMinutes();         | Run the task every thirty minutes                   |
| ->hourly();                     | Run the task every hour                             |  
| ->hourlyAt(17);                 | Run the task every hour at 17 mins past the hour    |
| ->daily();                      | Run the task every day at midnight                  |
| ->dailyAt('13:00');             | Run the task every day at 13:00                     |
| ->twiceDaily(1, 13);            | Run the task daily at 1:00 & 13:00                  |
| ->weekly();                     | Run the task every week                             |
| ->monthly();                    | Run the task every month                            |
| ->monthlyOn(4, '15:00');        | Run the task every month on the 4th at 15:00        |
| ->quarterly();                  | Run the task every quarter                          | 
| ->yearly();                     | Run the task every year                             |
| ->timezone('America/New_York'); | Set the timezone                                    | 
*---------------------------------*-----------------------------------------------------*
Enter fullscreen mode Exit fullscreen mode

Fonte: https://pt.stackoverflow.com/questions/249173/como-criar-um-cron-no-laravel

Top comments (0)