Run Cron Job Based on Condition in Laravel

Hello artisan in example i will discuss about how we can run Laravel task scheduling based on a condition. That mean i will run cron command only when satisfy the condition. We can do it in many ways. 

Here in this example i will share two ways that you can follow to run you custom cron job conditionally. It is pretty good that we can pass callback function every where in Laravel. Do you know that we can also pass call back in our cron command to run our cron job conditionally in laravel.

For example we need to run cron job on specific date and specific time once. For that what you can do?  See the below example code:

protected function schedule(Schedule $schedule)
    {
        $schedule->call(function(){
             info('Write your logic here');
        })->when(function (){
            return Carbon::createFromFormat('m/d/Y H:i:s', '15/07/2021 10:10:00')->isPast();
    });
}

 

Or you can follow this below method also:

protected function schedule(Schedule $schedule)
{
    $schedule-->command('command_goes_here')->when(function (){
      return \Carbon\Carbon::createFromFormat('m/d/Y H:i:s', '15/07/2021 10:10:00')->isPast() && \Carbon\Carbon::createFromFormat('m/d/Y H:i:s', '07/07/2021 10:12:00')->isPast();
    });
}

 

Read also: How to Generate QR Code in PHP Laravel

 

Hope it can help you!

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.