Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding stop functionality for graceful shutdown #59

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion sqs_listener/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def __init__(self, queue, **kwargs):
self._wait_time = kwargs.get('wait_time', 0)
self._max_number_of_messages = kwargs.get('max_number_of_messages', 1)
self._deserializer = kwargs.get("deserializer", json.loads)
self._should_listen = False

# must come last
if boto3_session:
Expand Down Expand Up @@ -139,7 +140,7 @@ def _initialize_client(self):

def _start_listening(self):
# TODO consider incorporating output processing from here: https://github.com/debrouwere/sqs-antenna/blob/master/antenna/__init__.py
while True:
while self._should_listen:
# calling with WaitTimeSecconds of zero show the same behavior as
# not specifiying a wait time, ie: short polling
messages = self._client.receive_message(
Expand All @@ -154,6 +155,8 @@ def _start_listening(self):
sqs_logger.debug(messages)
sqs_logger.info("{} messages received".format(len(messages['Messages'])))
for m in messages['Messages']:
if not self._should_listen:
break
receipt_handle = m['ReceiptHandle']
m_body = m['Body']
message_attribs = None
Expand Down Expand Up @@ -197,15 +200,22 @@ def _start_listening(self):
)

else:
if not self._should_listen:
break
time.sleep(self._poll_interval)
sqs_logger.info("client is not in listening state, stopping sqs listener")

def listen(self):
self._should_listen = True
sqs_logger.info("Listening to queue " + self._queue_name)
if self._error_queue_name:
sqs_logger.info("Using error queue " + self._error_queue_name)

self._start_listening()

def stop(self):
self._should_listen = False

def _prepare_logger(self):
logger = logging.getLogger('eg_daemon')
logger.setLevel(logging.INFO)
Expand Down