AWS SDK for JavaScript
Developer Guide for SDK v2

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:

Configuring the SDK

Configure the SDK for JavaScript by creating a global configuration object then setting the region for your code. In this example, the region is set to us-west-2.

// Load the SDK for JavaScript var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'us-west-2'});

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 AWS.config.update({region: 'REGION'}); // Create the SQS service object var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); var queueURL = "SQS_QUEUE_URL"; var params = { AttributeNames: [ "SentTimestamp" ], MaxNumberOfMessages: 1, MessageAttributeNames: [ "All" ], QueueUrl: queueURL }; sqs.receiveMessage(params, function(err, data) { if (err) { console.log("Receive Error", err); } else { var visibilityParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, VisibilityTimeout: 36000 // 10 hour timeout }; sqs.changeMessageVisibility(visibilityParams, function(err, data) { if (err) { console.log("Delete Error", err); } else { console.log("Timeout Changed", data); } }); } });

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

node sqs_changingvisibility.js

This sample code can be found here on GitHub.