2021-10-08 16:29:35 +01:00
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# Purpose:
2022-09-21 16:03:39 -06:00
# create_job_status_notification.rb demonstrates how to create a queue for handling notifications
2021-10-15 12:09:21 +01:00
# for an Amazon Elastic Transcoder job using the AWS SDK for Ruby.
2021-10-08 16:29:35 +01:00
2019-01-30 00:21:42 +00:00
# snippet-start:[elastictranscoder.ruby.create_sqs_notification_queue.import]
2024-09-25 15:25:54 -04:00
require 'aws-sdk-elastictranscoder'
require 'aws-sdk-sqs'
2019-01-29 21:49:23 +00:00
# Class which will poll SQS for job state notifications in a separate thread.
# This class is intended for batch-processing. If you are using a ruby-on-rails
# server, then a better implementation would be to subscribe your server
# directly to the notification topic and process the SNS messages directly.
class SqsQueueNotificationWorker
2022-09-20 17:57:59 -06:00
def initialize ( queue_url , options = { } )
2019-01-29 21:49:23 +00:00
options = { max_messages : 5 , visibility_timeout : 15 , wait_time_seconds : 5 } . merge ( options )
@queue_url = queue_url
@max_messages = options [ :max_messages ]
@visibility_timeout = options [ :visibility_timeout ]
@wait_time_seconds = options [ :wait_time_seconds ]
@handlers = [ ]
end
2019-01-30 04:50:30 -08:00
def start
2019-01-29 21:49:23 +00:00
@shutdown = false
2019-01-30 04:50:30 -08:00
@thread = Thread . new { poll_and_handle_messages }
2019-01-29 21:49:23 +00:00
end
2019-01-30 04:50:30 -08:00
def stop
2019-01-29 21:49:23 +00:00
@shutdown = true
end
2019-01-30 04:50:30 -08:00
2019-01-29 21:49:23 +00:00
def add_handler ( handler )
@handlers << handler
end
2019-01-30 04:50:30 -08:00
2019-01-29 21:49:23 +00:00
def remove_handler ( handler )
@handlers -= [ handler ]
end
2019-01-30 04:50:30 -08:00
def poll_and_handle_messages
2022-09-19 18:07:50 -06:00
sqs_client = Aws :: SQS :: Client . new
2019-01-30 04:50:30 -08:00
until @shutdown
2019-01-29 21:49:23 +00:00
sqs_messages = sqs_client . receive_message (
queue_url : @queue_url ,
max_number_of_messages : @max_messages ,
2019-01-30 04:50:30 -08:00
wait_time_seconds : @wait_time_seconds
) . data [ :messages ]
next if sqs_messages . nil?
2019-01-29 21:49:23 +00:00
sqs_messages . each do | sqs_message |
2024-09-25 15:25:54 -04:00
notification = JSON . parse ( JSON . parse ( sqs_message [ :body ] ) [ 'Message' ] )
2019-01-29 21:49:23 +00:00
@handlers . each do | handler |
handler . call ( notification )
sqs_client . delete_message ( queue_url : @queue_url , receipt_handle : sqs_message [ :receipt_handle ] )
end
end
end
end
end
2019-01-30 00:21:42 +00:00
# snippet-end:[elastictranscoder.ruby.create_sqs_notification_queue.import]