Skip to content

Instantly share code, notes, and snippets.

@FHeilmann
Last active September 19, 2016 11:23
Show Gist options
  • Save FHeilmann/069150d1886fbf2dae12476ef6f7b8c1 to your computer and use it in GitHub Desktop.
Save FHeilmann/069150d1886fbf2dae12476ef6f7b8c1 to your computer and use it in GitHub Desktop.
Create an asynchronous interruptible loop with python 2
from concurrent import futures
import time
# Container class for our worker loop.
# Wrapping the loop in a class allows us to create
# an instance which hosts an interrupt variable which
# we can access after we submitted the loop to the Executor.
# That way we can cancel the loop from the outside.
class Worker(object):
# Set the interrupted state to False to allow looping
def __init__(self):
self.interrupt = False
# Actual asynchronous operation
def do_work(self):
# Loop until interrupted
while not self.interrupt:
# Print something and sleep a bit
print("Doing work!")
time.sleep(1)
# Update interrupted state
def interrupt(self):
self.interupt = True
#Only works with threads, as accessing variables across processes doesnt work
executor = futures.ThreadPoolExecutor(max_workers=1)
# Instantiate container class
worker = Worker()
# Submit the loop to the executor. Returns immediately
worker_future = executor.submit(worker.do_work)
# Wait some time
time.sleep(10)
# Interrupt the loop. The worker loop will run until the
# interrupt variable is checked the next time. It is the
# responsibility of the developer to check for the interrupted
# state variable a sufficient amount of times to shut down
# the loop in due time. For example, if using socket operations
# a timeout should be specified, since an infinitely blocking
# socket operation would render this approach useless.
worker.interrupt()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment