无法在无限循环中接收来自SQS的消息

时间:2016-06-29 23:46:02

标签: javascript node.js amazon-sqs

我在无限循环中调用sqs.receiveMessage(receiveParams, function(err, data){})。但它根本没有被触发。

var receiveParams = {
    QueueUrl: queueUrl,
    VisibilityTimeout: 40
};

while (true)
{
    console.log("before");
    setTimeout(function() {
        sqs.receiveMessage(receiveParams, function(err,data){
            console.log("Calling");
            if (err) {
                console.log(err);
            }
            else {
                console.log(data);
                if (data.Messages != null)
                {
                    console.log("Executing my fuction");
                    myFunction();
                }
            }
        });
    }, 10000);

    console.log("after");
}

如果我在循环外执行sqs.receiveMessage(),它可以正常工作。我不知道为什么它永远不会在循环中被调用。我猜我的超时设置有问题。因为我的循环将在“之前”和“之后”记录而没有时间延迟。任何帮助?

1 个答案:

答案 0 :(得分:2)

您的代码充斥着无限量setTimeout命令的节点事件堆栈。

也就是说,在代码运行时,它将首先生成一个任务来执行sqs.receiveMessage调用 - 它将在一秒钟之后执行。但是,在第一个任务启动之前,在while循环的第二次迭代中,它将再次产生另一个类似的任务。因此,在一个秒的时间范围内,您将拥有相当于1毫秒的相关工作。这就解释了为什么你会看到这些照片。

您无法获得服务的正确回复的原因可能是它具有“防洪”功能。启用。例如。如果在同一个呼叫者的某个时间内有太多请求,那么它将忽略呼叫者X的时间量。

您可能希望改用setInterval
请参阅https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval

  

<强>的setInterval
  重复调用函数或执行带有修复的代码片段   每次通话之间的时间延迟。返回intervalID。

示例:

// repeat the call every 10seconds
setInterval(function() {
    sqs.receiveMessage(receiveParams, function(err,data){
        console.log("Calling");
        if (err) {
            console.log(err);
        }
        else {
            console.log(data);
            if (data.Messages != null)
            {
                console.log("Executing my fuction");
                myFunction();
            }
        }
    });
}, 10000);

让我知道你如何使用它。如果需要,很乐意进一步提供帮助。

相关问题