Laravel 5 schedule job every 30 seconds
Asked Answered
G

2

2

I am using Laravel schedule to run cron jobs.

In my crontab I have added (with correct path to my project):

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

Now my App\Console\Kernel.php looks like:

protected function schedule(Schedule $schedule)
{
        $schedule->command('investments:calculate_interests')->everyMinute();
        $schedule->call('\App\Http\Controllers\UsersController@testEvent')->everyMinute();
}

Using it like that I successfully run jobs every minute. But how I can change it to run them on every 10 or 20 or 30 seconds?

Gemma answered 21/4, 2016 at 15:9 Comment(1)
Possible duplicate of Running a Laravel method every 30 secondsCuisine
T
5

I solved it with this code:

public function handle()
{
    $count = 0;
    while ($count < 59) {
        $startTime =  Carbon::now();

        $this->travelsRequestsDriversRepository->beFreeRequestAfterTime();

        $endTime = Carbon::now();
        $totalDuration = $endTime->diffInSeconds($startTime);
        if($totalDuration > 0) {
            $count +=  $totalDuration;
        }
        else {
            $count++;
        }
        sleep(1);
    }


}

and in cron table add command of this.

* * * * * /usr/local/php56/bin/php56 /home/hamshahr/domains/hamshahrapp.com/project/artisan taxis:beFreeTaxis 1>> /dev/null 2>&1
Thriller answered 16/2, 2018 at 10:32 Comment(0)
G
-2

It's not working like Alexey Mezenin suggested, but he gave me an idea where to test some solutions.

You can add loop with timer not to

protected function schedule(Schedule $schedule)

but direct into the command / event or other what you want to loop.

For example, I was running a command, so inside the command I added:

public function handle()
{
        \App\Investment::calculate();
        sleep(30);
        \App\Investment::calculate();
}

And now my command works every 30 seconds.

Gemma answered 21/4, 2016 at 20:13 Comment(1)
This method is going to block other commands from being executed. How can I not block other commands, but still execute this every 30 seconds?Foldboat

© 2022 - 2024 — McMap. All rights reserved.