There's more...

In this section, we covered how to cancel a scheduled alarm, but if this callback was polling the status of a background thread, you might wonder how to stop the thread as well.

Unfortunately, there is no official API to gracefully stop a Thread instance. If you have defined a custom subclass, you might need to include a flag that is periodically checked inside its run() method:

class MyAsyncAction(threading.Thread):
def __init__(self):
super().__init__()
self.do_stop = False

def run(self):
# Start execution...
if not self.do_stop:
# Continue execution...

Then, this flag can be externally modified by setting thread.do_stop = True when invoking after_cancel() also to stop the thread.

Obviously, this approach will heavily depend on the operations performed inside the run() method—for instance, this mechanism is easier to implement if it consists of a loop, because you can perform this check between each iteration.

Starting from Python 3.4, you can use the asyncio module, which includes classes and functions to manage asynchronous operations, including cancellations. Even though this module is outside the scope of this book, we recommend you explore it if you face more complex scenarios.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset