Laravel Cron Job Schedule One Time Custom Setup Example

By Hardik Savani March 1, 2021 Category : Laravel

Today, i would like to show you One time custom cron schedule in laravel. if you have question about laravel schedule specific time then i will give simple example with solution. let’s discuss about laravel cron one time only specific date time one time. this example will help you laravel cron one time only.

Few days ago i written how to setup cron dynamic in laravel. you can also see from here: Click Here. you can easily use with laravel 6, laravel 7 and laravel 8.

so if you need to run cron job on specific date and time once. for example i organize one function on 07/07/2021 10:10:00 and i need to send notification of that event then i just need to send one time only, not early or not monthly. that things you can do it using when function. so let's see bellow file code:

Example 1: app/Console/Kernel.php

<?php

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 = [

];

/**

* Define the application's command schedule.

*

* @param \Illuminate\Console\Scheduling\Schedule $schedule

* @return void

*/

protected function schedule(Schedule $schedule)

{

$schedule->call(function(){

\Log::info('Write your logic here');

})->when(function (){

return \Carbon\Carbon::createFromFormat('m/d/Y H:i:s', '07/07/2021 10:10:00')->isPast();

});

}

/**

* Register the commands for the application.

*

* @return void

*/

protected function commands()

{

$this->load(__DIR__.'/Commands');

require base_path('routes/console.php');

}

}

Example 2: app/Console/Kernel.php

<?php

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 = [

];

/**

* Define the application's command schedule.

*

* @param \Illuminate\Console\Scheduling\Schedule $schedule

* @return void

*/

protected function schedule(Schedule $schedule)

{

$schedule-->command('your_command_here')->when(function (){

return \Carbon\Carbon::createFromFormat('m/d/Y H:i:s', '07/07/2021 10:10:00')->isPast() && \Carbon\Carbon::createFromFormat('m/d/Y H:i:s', '07/07/2021 10:12:00')->isPast();

});

}

/**

* Register the commands for the application.

*

* @return void

*/

protected function commands()

{

$this->load(__DIR__.'/Commands');

require base_path('routes/console.php');

}

}

I hope it can help you....

Tags :