Suhail Gupta
Suhail Gupta

Reputation: 23206

Check for an incoming message in aws sqs

How does my function continuously check for an incoming message? The following function exits, after receiving a message. Considering, long polling has been enabled for the queue how do I continuously check for a new message?

function checkMessage(){
    var params = {
                QueueUrl : Constant.QUEUE_URL,
                VisibilityTimeout: 0,
                WaitTimeSeconds: 0
            }
    sqs.receiveMessage(params,(err,data) => {
        if(data){
            console.log("%o",data);
        }
    });
}

Upvotes: 1

Views: 3336

Answers (3)

Odetara Bolaji
Odetara Bolaji

Reputation: 1

(function checkMessage(){ var params = { QueueUrl : Constant.QUEUE_URL, VisibilityTimeout: 0, WaitTimeSeconds: 0 } sqs.receiveMessage(params,(err,data) => { if(data){ console.log("%o",data); } checkMessage() }); })()

To continuously check for an incoming message in your aws sqs you will want to recusrsively call the aws sqs whenever a data is returned.

Upvotes: 0

Dave Maple
Dave Maple

Reputation: 8402

var processMessages = (function (err, data) {
    if (data.Messages) {

        for (i = 0; i < data.Messages.length; i++) {
            var message = data.Messages[i];
            var body = JSON.parse(message.Body);

            // process message
            // delete if successful
        }
    }
});

while (true) {
    sqs.receiveMessage({
        QueueUrl: sqsQueueUrl,
        MaxNumberOfMessages: 5, // how many messages to retrieve in a batch
        VisibilityTimeout: 60,  // how long until these messages are available to another consumer
        WaitTimeSeconds: 15     // how many seconds to wait for messages before continuing 
    }, processMessages);
}

Upvotes: 3

John Rotenstein
John Rotenstein

Reputation: 269081

Your function would need to continually poll Amazon SQS.

Long Polling will delay a response by up to 20 seconds if there are no messages available. If a message becomes available during that period, it will be immediately returned. If there is no message after 20 seconds, it returns without providing a message.

Therefore, your function would need to poll SQS again (perhaps doing something else in the meantime).

Upvotes: 5

Related Questions