Laravel 调度:每秒执行一个命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38586498/
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 14:12:51  来源:igfitidea点击:

Laravel schedular: execute a command every second

phplaravelcron

提问by Naveed

I have a project that needs to send notifications via WebSockets continuously. It should connect to a device that returns the overall status in string format. The system processes it and then sends notifications based on various conditions.

我有一个项目需要通过 WebSockets 持续发送通知。它应该连接到以字符串格式返回整体状态的设备。系统对其进行处理,然后根据各种条件发送通知。

Since the scheduler can repeat a task as early as a minute, I need to find a way to execute the function every second.

由于调度程序最早可以在一分钟内重复执行一项任务,因此我需要找到一种每秒执行该函数的方法。

Here is my app/Console/Kernel.php:

这是我的app/Console/Kernel.php

<?php    
  ...    
class Kernel extends ConsoleKernel
{
    ...
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function(){
            // connect to the device and process its response
        })->everyMinute();
    }
}

PS: If you have a better idea to handle the situation, please share your thoughts.

PS:如果你有更好的想法来处理这种情况,请分享你的想法。

回答by Alexey Shokov

Usually, when you want more granularity than 1 minute, you have to write a daemon.

通常,当您想要超过 1 分钟的粒度时,您必须编写一个守护进程。

I advise you to try, now it's not so hard as it was some years ago. Just start with a simple loop inside a CLI command:

我劝你试试,现在没有几年前那么难了。只需从 CLI 命令中的一个简单循环开始:

while (true) {
    doPeriodicStuff();

    sleep(1);
}

One important thing: run the daemon via supervisord. You can take a look at articles about Laravel's queue listener setup, it uses the same approach (a daemon + supervisord). A config section can look like this:

一件重要的事情:通过supervisord运行守护进程。您可以查看有关 Laravel 队列侦听器设置的文章,它使用相同的方法(守护进程 + 主管)。配置部分可能如下所示:

[program:your_daemon]
command=php artisan your:command --env=your_environment
directory=/path/to/laravel
stdout_logfile=/path/to/laravel/app/storage/logs/your_command.log
redirect_stderr=true
autostart=true
autorestart=true

回答by Inno

$schedule->call(function(){
    while (some-condition) {
        runProcess();
    }
})->name("someName")->withoutOverlapping();

Depending on how long your runProcess()takes to execute, you can use sleep(seconds)to have more fine tuning.

根据runProcess()执行所需的时间,您可以sleep(seconds)进行更多的微调。

some-conditionis normally a flag that you can change any time to have control on the infinite loop. e.g. you can use file_exists(path-to-flag-file)to manually start or stop the process any time you need.

some-condition通常是一个标志,您可以随时更改以控制无限循环。例如,您可以file_exists(path-to-flag-file)在需要时随时手动启动或停止该过程。

回答by Hamid Naghipour

for per second you can add command to cron job

您可以每秒向 cron 作业添加命令

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

and in command :

并在命令中:

<?php

namespace App\Console\Commands;

use App\Contracts\Repositories\TaxiRepository;
use App\Contracts\Repositories\TravelRepository;
use App\Contracts\Repositories\TravelsRequestsDriversRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;

class beFreeRequest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'taxis:beFreeRequest';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'change is active to 0 after 1 min if yet is 1';

    /**
     * @var TravelsRequestsDriversRepository
     */
    private $travelsRequestsDriversRepository;

    /**
     * Create a new command instance.
     * @param TravelsRequestsDriversRepository $travelsRequestsDriversRepository
     */
    public function __construct(
        TravelsRequestsDriversRepository $travelsRequestsDriversRepository
    )
    {
        parent::__construct();
        $this->travelsRequestsDriversRepository = $travelsRequestsDriversRepository;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    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);
        }

    }
}

回答by Riyaz Shaikh

You can try and duplicate the jobs every second * 60 times using sleep(1).

您可以尝试使用 sleep(1) 每秒 * 60 次复制作业。