iotile.core.utilities.stoppable_thread

A thread that can be stopped

Module Contents

class StoppableWorkerThread(routine, timeout=0.1, args=None, kwargs=None)

Bases:threading.Thread

A worker thread that calls a worker function periodically.

This class takes a single callable function and calls that function with *args and **kwargs in a loop with a configurable delay between each invocation. There is a public stop() method that will kill the thread after the next time the callable function returns.

If you pass a generator function then the function is called in a loop with next() until it raises a StopIteration exception at which point the thread is closed. Exceptions thrown from the generator cause the thread to exit immediately. The stop condition of the thread is checked every time the generator yields.

generator

Whether this thread is running a generator function or not

run(self)

The target routine called to start thread activity.

If the thread is created with a generator function, this iterates the generator and checks for a stop condition between each iteration.

If the thread is created with a normal function, that function is called in a loop with the stop condition checked between each invocation.

wait_running(self, timeout=None)

Wait for the thread to pass control to its routine.

Args:
timeout (float): The maximum amount of time to wait
stop(self, timeout=None, force=False)

Stop the worker thread and synchronously wait for it to finish.

Args:
timeout (float): The maximum time to wait for the thread to stop
before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError is not raised and the thread is just marked as a daemon thread so that it does not block cleanly exiting the process.
force (bool): If true and the thread does not exit in timeout seconds
no error is raised since the thread is marked as daemon and will be killed when the process exits.
signal_stop(self)

Signal that the worker thread should stop but don’t wait.

This function is useful for stopping multiple threads in parallel when combined with wait_stopped().

wait_stopped(self, timeout=None, force=False)

Wait for the thread to stop.

You must have previously called signal_stop or this function will hang.

Args:
timeout (float): The maximum time to wait for the thread to stop
before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError is not raised and the thread is just marked as a daemon thread so that it does not block cleanly exiting the process.
force (bool): If true and the thread does not exit in timeout seconds
no error is raised since the thread is marked as daemon and will be killed when the process exits.