如何每X毫秒执行一次功能?

时间:2018-10-15 16:59:06

标签: javascript node.js express timeout mqtt

对于javascript和node来说还很新,目前可以在node.js应用中使用, 该应用程序使用express和mongoDB,其想法是通过webhook,websocket和mqtt监听某些第三方服务,并将所有数据存储到mongoDB中。

但是我有一个小问题,一些第三方应用程序经常向我发送数据, 例如,mqtt流每秒发送大约2条消息,我只需要每分钟存储其中一条消息。

这是我将mqtt实例到app.js中的方式

var mqttHandler = require('./mqtt/mqtt_handler'); //mqtt
var mqttClient = new mqttHandler(); //mqtt
mqttClient.connect(); //mqtt

这是我的mqttHandler.js:

onst mqtt = require('mqtt');

class MqttHandler {
  constructor() {
    this.mqttClient = null;
    this.host = 'mqtts://host';
    this.username = 'foo'; // mqtt credentials if these are needed to connect
    this.password = 'mypassqword';
    this.port = 8083;
    this.protocol = 'MQTTS';
    this.client = 'bar'
  }

  connect() {
    // Connect mqtt with credentials (in case of needed, otherwise we can omit 2nd param)
    this.mqttClient = mqtt.connect(this.host, {password : this.password, username : this.username, port: this.port});

    // Mqtt error calback
    this.mqttClient.on('error', (err) => {
      console.log(err);
      this.mqttClient.end();
    });

    // Connection callback
    this.mqttClient.on('connect', () => {
      //console.log(`mqtt client connected`);
    });

    // mqtt subscriptions
    this.mqttClient.subscribe('/the_subscription');
    // When a message arrives, console.log it
    this.mqttClient.on('message', function (topic, message) {
      console.log(message.toString())
    });

    this.mqttClient.on('close', () => {
      //console.log(`mqtt client disconnected`);
    });
  }

  // Sends a mqtt message to topic: mytopic
  sendMessage(message) {
    this.mqttClient.publish('mytopic', message);
  }
}

module.exports = MqttHandler;

我正在阅读有关setInterval和setTimeout的内容,但是我无法弄清楚如何实现这些功能以强制给定的功能每X秒运行一次(没有算术调用了多少次)

对于mqtt,webohooks和/或websocket,是否可以有类似/通用的方法来实现此功能?

我从一个教程中获取了有关如何实现mqtt的示例,正​​如我所说,它的工作原理非常完美,对javascript来说还很新。

2 个答案:

答案 0 :(得分:0)

使用setInterval的一种简单方法是定期设置标志,并在发布消息后清除它。忽略任何其他消息,直到间隔功能再次设置该标志为止。

let readyToPost = false;
setInterval(function(){ readyToPost = true; }, 1000);

在您的职能中:

function connect() {
  if (!readyToPost) return;  // do nothing
  readyToPost = false;
  // rest of your code
}

答案 1 :(得分:0)

还有一个 mqtt 模块的包装器:

#include <stdio.h>  
#include <stdlib.h>  
#include <conio.h>  
#include <time.h>  
#include <unistd.h>  

int main()
{

    printf("\nYou approach him, you try to take him by the legs from behind.\n");
    Sleep(1500);
    
    
    while (!kbhit())
    {

        printf("PRESS C !!!\n");
        int c = getch();
        if ((c == 'c' || c == 'C') && sleep(3) != 0)
        {
            printf("Can you pick him up by the paws and\n");
            break;
        }
        else if((c != 'c' || c != 'C') && sleep == 0)         //damage 40
        {
            printf("\nYou failed to catch it and as it turns around it hurts you with its tail.\n");
            getch();
            break;
        }
    }
    printf("Jhon takes out his Swiss Army knife and stabs him in the throat, killing him.\n");
}