Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can run a task every X second with Laravel?

Tags:

laravel-5

Hy guys, I have read the chapter called scheduling of Laravel's documentation, but I haven't found much information. I'm trying to customize the execution of a task to make it run every 30 seconds. Is there a solution ? Sorry for my english and have a good day.

like image 829
therock24 Avatar asked Dec 29 '25 13:12

therock24


1 Answers

By default CRON tasks are scheduled in minimal period 1 minute, but there is workaround for your issue.

In Console Kernel you should do something like this:

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
     $schedule->command('your_command:run', ['--delay'=> 0])->everyMinute();
     $schedule->command('your_command:run', ['--delay'=> 30])->everyMinute();
}

In your Command class you should define the $signature variable that can take the delay parameter.

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'your_command:run {--delay= : Number of seconds to delay command}';

In the handle method you should read value of this parameter and sleep this task for specific number of second using built-in sleep() function.

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    // code
    sleep(intval($this->option('delay')));
}

This solution will run your task every 30 seconds, you can multiply number of task with different delay. In this case you need to edit schedule method in Kernel class.

like image 154
Hubert Sadecki Avatar answered Jan 03 '26 12:01

Hubert Sadecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!