Managing Visibility Timeout in Amazon SQS - AWS SDK for JavaScript

Managing Visibility Timeout in Amazon SQS

JavaScript code example that applies to Node.js execution

This Node.js code example shows:

  • How to specify the time interval during which messages received by a queue are not visible.

The Scenario

In this example, a Node.js module is used to manage visibility timeout. The Node.js module uses the SDK for JavaScript to manage visibility timeout by using this method of the AWS.SQS client class:

For more information about Amazon SQS visibility timeout, see Visibility Timeout in the Amazon Simple Queue Service Developer Guide.

Prerequisite Tasks

To set up and run this example, you must first complete these tasks:

Changing the Visibility Timeout

Create a Node.js module with the file name sqs_changingvisibility.js. Be sure to configure the SDK as previously shown. To access Amazon Simple Queue Service, create an AWS.SQS service object. Receive the message from the queue.

Upon receipt of the message from the queue, create a JSON object containing the parameters needed for setting the timeout, including the URL of the queue containing the message, the ReceiptHandle returned when the message was received, and the new timeout in seconds. Call the changeMessageVisibility method.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk') // Set the region to us-west-2 AWS.config.update({ region: 'us-west-2' }) // Create the SQS service object var sqs = new AWS.SQS({ apiVersion: '2012-11-05' }) var queueURL = 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' var params = { AttributeNames: ['SentTimestamp'], MaxNumberOfMessages: 1, MessageAttributeNames: ['All'], QueueUrl: queueURL } sqs.receiveMessage(params, function (err, data) { if (err) { console.log('Receive Error', err) } else { // Make sure we have a message if (data.Messages != null) { var visibilityParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, VisibilityTimeout: 20 // 20 second timeout } sqs.changeMessageVisibility(visibilityParams, function (err, data) { if (err) { console.log('Delete Error', err) } else { console.log('Timeout Changed', data) } }) } else { console.log('No messages to change') } } })

To run the example, type the following at the command line.

node sqs_changingvisibility.js

This sample code can be found here on GitHub.