计划Laravel:每秒执行一次命令 [英] Laravel schedular: execute a command every second

查看:150
本文介绍了计划Laravel:每秒执行一次命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

由于调度程序可以在一分钟内重复执行任务,因此我需要找到一种每秒执行一次功能的方法.

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

这是我的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:如果您有更好的主意来处理这种情况,请分享您的想法.

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

推荐答案

通常,当您希望粒度超过1分钟时,必须编写一个守护程序.

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

我建议您尝试一下,现在不像几年前那样困难.只需从CLI命令中的简单循环开始:

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:

while (true) {
    doPeriodicStuff();

    sleep(1);
}

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

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:

[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

这篇关于计划Laravel:每秒执行一次命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆