Laravel 5 每 30 秒安排一次工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36773693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:38:44  来源:igfitidea点击:

Laravel 5 schedule job every 30 seconds

laravellaravel-5scheduled-taskslaravel-5.2laravel-scheduler

提问by el valuta

I am using Laravel schedule to run cron jobs.

我正在使用 Laravel 计划来运行 cron 作业。

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

在我的 crontab 中,我添加了(使用正确的项目路径):

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

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

现在我的 App\Console\Kernel.php 看起来像:

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?

像这样使用它我每分钟都成功地运行作业。但是我如何更改它以每 10 或 20 或 30 秒运行一次?

回答by Hamid Naghipour

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.

并在 cron 表中添加此命令。

* * * * * /usr/local/php56/bin/php56 /home/hamshahr/domains/hamshahrapp.com/project/artisan taxis:beFreeTaxis 1>> /dev/null 2>&1

回答by el valuta

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

它不像 Alexey Mezenin 建议的那样工作,但他让我知道在哪里测试一些解决方案。

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.

现在我的命令每 30 秒运行一次。