Skip to content

Instantly share code, notes, and snippets.

@jqtrde
Forked from perrygeo/send_message.py
Created April 27, 2018 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jqtrde/d119ec42b5f7599de2e443051061d1de to your computer and use it in GitHub Desktop.
Save jqtrde/d119ec42b5f7599de2e443051061d1de to your computer and use it in GitHub Desktop.
import random
import time
import json
import threading
import click
def send_message(msg, async=True):
"""Logs the msg (presumably a JSON object) to firehose
If async is true, use a background thread
Based on
http://sebastiandahlgren.se/2014/06/27/running-a-method-as-a-background-thread-in-python/
"""
def send(msg=msg):
# Simulates a system where the IO could take up to 5 seconds
time.sleep(random.random() * 5)
try:
print(f"Sending {msg}")
except Exception:
pass # swallow any and all exceptions
if async:
thread = threading.Thread(target=send)
thread.daemon = True
thread.start()
else:
send()
@click.command()
@click.option('--async/--sync', is_flag=True, default=True)
def main(async):
click.echo("Async..." if async else "Sync...")
for i in range(10):
send_message(json.dumps({'a': i}), async=async)
print("I'm done logging, start the heavy processing")
time.sleep(5)
print("I'm done processing")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment