API

Executors

class futurist.GreenThreadPoolExecutor(max_workers=1000)

Executor that uses a green thread pool to execute calls asynchronously.

See: https://docs.python.org/dev/library/concurrent.futures.html and http://eventlet.net/doc/modules/greenpool.html for information on how this works.

It gathers statistics about the submissions executed for post-analysis...

alive

Accessor to determine if the executor is alive/active.

statistics

ExecutorStatistics about the executors executions.

submit(fn, *args, **kwargs)

Submit some work to be executed (and gather statistics).

Parameters:
  • args (list) – non-keyworded arguments
  • kwargs (dictionary) – key-value arguments
class futurist.ProcessPoolExecutor(max_workers=None)

Executor that uses a process pool to execute calls asynchronously.

It gathers statistics about the submissions executed for post-analysis...

See: https://docs.python.org/dev/library/concurrent.futures.html

alive

Accessor to determine if the executor is alive/active.

statistics

ExecutorStatistics about the executors executions.

submit(fn, *args, **kwargs)

Submit some work to be executed (and gather statistics).

class futurist.SynchronousExecutor(green=False)

Executor that uses the caller to execute calls synchronously.

This provides an interface to a caller that looks like an executor but will execute the calls inside the caller thread instead of executing it in a external process/thread for when this type of functionality is useful to provide...

It gathers statistics about the submissions executed for post-analysis...

__init__(green=False)

Synchronous executor constructor.

Parameters:green (bool) – when enabled this forces the usage of greened lock classes and green futures (so that the internals of this object operate correctly under eventlet)
alive

Accessor to determine if the executor is alive/active.

restart()

Restarts this executor (iff previously shutoff/shutdown).

NOTE(harlowja): clears any previously gathered statistics.

statistics

ExecutorStatistics about the executors executions.

submit(fn, *args, **kwargs)

Submit some work to be executed (and gather statistics).

class futurist.ThreadPoolExecutor(max_workers=None)

Executor that uses a thread pool to execute calls asynchronously.

It gathers statistics about the submissions executed for post-analysis...

See: https://docs.python.org/dev/library/concurrent.futures.html

alive

Accessor to determine if the executor is alive/active.

statistics

ExecutorStatistics about the executors executions.

submit(fn, *args, **kwargs)

Submit some work to be executed (and gather statistics).

Futures

class futurist.Future

Represents the result of an asynchronous computation.

add_done_callback(fn)

Attaches a callable that will be called when the future finishes.

Args:
fn: A callable that will be called with this future as its only
argument when the future completes or is cancelled. The callable will always be called by a thread in the same process in which it was added. If the future has already completed or been cancelled then the callable will be called immediately. These callables are called in the order that they were added.
cancel()

Cancel the future if possible.

Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed.

cancelled()

Return True if the future has cancelled.

done()

Return True of the future was cancelled or finished executing.

exception(timeout=None)

Return the exception raised by the call that the future represents.

Args:
timeout: The number of seconds to wait for the exception if the
future isn’t done. If None, then there is no limit on the wait time.
Returns:
The exception raised by the call that the future represents or None if the call completed without raising.
Raises:

CancelledError: If the future was cancelled. TimeoutError: If the future didn’t finish executing before the given

timeout.
exception_info(timeout=None)

Return a tuple of (exception, traceback) raised by the call that the future represents.

Args:
timeout: The number of seconds to wait for the exception if the
future isn’t done. If None, then there is no limit on the wait time.
Returns:
The exception raised by the call that the future represents or None if the call completed without raising.
Raises:

CancelledError: If the future was cancelled. TimeoutError: If the future didn’t finish executing before the given

timeout.
result(timeout=None)

Return the result of the call that the future represents.

Args:
timeout: The number of seconds to wait for the result if the future
isn’t done. If None, then there is no limit on the wait time.
Returns:
The result of the call that the future represents.
Raises:

CancelledError: If the future was cancelled. TimeoutError: If the future didn’t finish executing before the given

timeout.

Exception: If the call raised then that exception will be raised.

running()

Return True if the future is currently executing.

set_exception(exception)

Sets the result of the future as being the given exception.

Should only be used by Executor implementations and unit tests.

set_exception_info(exception, traceback)

Sets the result of the future as being the given exception and traceback.

Should only be used by Executor implementations and unit tests.

set_result(result)

Sets the return value of work associated with the future.

Should only be used by Executor implementations and unit tests.

set_running_or_notify_cancel()

Mark the future as running or process any cancel notifications.

Should only be used by Executor implementations and unit tests.

If the future has been cancelled (cancel() was called and returned True) then any threads waiting on the future completing (though calls to as_completed() or wait()) are notified and False is returned.

If the future was not cancelled then it is put in the running state (future calls to running() will return True) and True is returned.

This method should be called by Executor implementations before executing the work associated with this future. If this method returns False then the work should not be executed.

Returns:
False if the Future was cancelled, True otherwise.
Raises:
RuntimeError: if this method was already called or if set_result()
or set_exception() was called.
class futurist.GreenFuture

Represents the result of an asynchronous computation.

Periodics

class futurist.periodics.PeriodicWorker(callables, log=None, executor_factory=None, cond_cls=<function Condition>, event_cls=<function Event>, schedule_strategy='last_started', now_func=<function monotonic>)

Calls a collection of callables periodically (sleeping as needed...).

NOTE(harlowja): typically the start() method is executed in a background thread so that the periodic callables are executed in the background/asynchronously (using the defined periods to determine when each is called).

BUILT_IN_STRATEGIES = {'last_started_jitter': (<function _last_started_strategy_with_jitter at 0x2b65f2e1c668>, <function _now_plus_periodicity at 0x2b65f2e1c1b8>), 'last_finished': (<function _last_finished_strategy at 0x2b65f2e1c050>, <function _now_plus_periodicity at 0x2b65f2e1c1b8>), 'aligned_last_finished': (<function _aligned_last_finished_strategy at 0x2b65f2e1c140>, <function _now_plus_periodicity at 0x2b65f2e1c1b8>), 'last_finished_jitter': (<function _last_finished_strategy_with_jitter at 0x2b65f2e1c6e0>, <function _now_plus_periodicity at 0x2b65f2e1c1b8>), 'last_started': (<function _last_started_strategy at 0x2b65f2e1c0c8>, <function _now_plus_periodicity at 0x2b65f2e1c1b8>), 'aligned_last_finished_jitter': (<function _aligned_last_finished_strategy_with_jitter at 0x2b65f2e1c758>, <function _now_plus_periodicity at 0x2b65f2e1c1b8>)}

Built in scheduling strategies (used to determine when next to run a periodic callable).

The first element is the strategy to use after the initial start and the second element is the strategy to use for the initial start.

These are made somewhat pluggable so that we can easily add-on different types later (perhaps one that uses a cron-style syntax for example).

DEFAULT_JITTER = Fraction(1, 20)

Default jitter percentage the built-in strategies (that have jitter support) will use.

MAX_LOOP_IDLE = 30

Max amount of time to wait when running (forces a wakeup when elapsed).

__init__(callables, log=None, executor_factory=None, cond_cls=<function Condition>, event_cls=<function Event>, schedule_strategy='last_started', now_func=<function monotonic>)

Creates a new worker using the given periodic callables.

Parameters:
  • callables (iterable) – a iterable of tuple objects previously decorated with the periodic() decorator, each item in the iterable is expected to be in the format of (cb, args, kwargs) where cb is the decorated function and args and kwargs are any positional and keyword arguments to send into the callback when it is activated (both args and kwargs may be provided as none to avoid using them)
  • log (logger) – logger to use when creating a new worker (defaults to the module logger if none provided), it is currently only used to report callback failures (if they occur)
  • executor_factory (callable) – factory callable that can be used to generate executor objects that will be used to run the periodic callables (if none is provided one will be created that uses the SynchronousExecutor class)
  • cond_cls (callable) – callable object that can produce threading.Condition (or compatible/equivalent) objects
  • event_cls (callable) – callable object that can produce threading.Event (or compatible/equivalent) objects
  • schedule_strategy (string) – string to select one of the built-in strategies that can return the next time a callable should run
  • now_func (callable) – callable that can return the current time offset from some point (used in calculating elapsed times and next times to run)
add(cb, *args, **kwargs)

Adds a new periodic callback to the current worker.

Parameters:cb (callable) – a callable object/method/function previously decorated with the periodic() decorator
classmethod create(objects, exclude_hidden=True, log=None, executor_factory=None, cond_cls=<function Condition>, event_cls=<function Event>, schedule_strategy='last_started', now_func=<function monotonic>)

Automatically creates a worker by analyzing object(s) methods.

Only picks up methods that have been tagged/decorated with the periodic() decorator (does not match against private or protected methods unless explicitly requested to).

Parameters:
  • objects (iterable) – the objects to introspect for decorated members
  • exclude_hidden (bool) – exclude hidden members (ones that start with an underscore)
  • log (logger) – logger to use when creating a new worker (defaults to the module logger if none provided), it is currently only used to report callback failures (if they occur)
  • executor_factory (callable) – factory callable that can be used to generate executor objects that will be used to run the periodic callables (if none is provided one will be created that uses the SynchronousExecutor class)
  • cond_cls (callable) – callable object that can produce threading.Condition (or compatible/equivalent) objects
  • event_cls (callable) – callable object that can produce threading.Event (or compatible/equivalent) objects
  • schedule_strategy (string) – string to select one of the built-in strategies that can return the next time a callable should run
  • now_func (callable) – callable that can return the current time offset from some point (used in calculating elapsed times and next times to run)
reset()

Resets the workers internal state.

start(allow_empty=False)

Starts running (will not return until stop() is called).

Parameters:allow_empty (bool) – instead of running with no callbacks raise when this worker has no contained callables (this can be set to true and add() can be used to add new callables on demand), note that when enabled and no callbacks exist this will block and sleep (until either stopped or callbacks are added)
stop()

Sets the tombstone (this stops any further executions).

wait(timeout=None)

Waits for the start() method to gracefully exit.

An optional timeout can be provided, which will cause the method to return within the specified timeout. If the timeout is reached, the returned value will be False.

Parameters:timeout (float/int) – Maximum number of seconds that the wait() method should block for
futurist.periodics.periodic(spacing, run_immediately=False)

Tags a method/function as wanting/able to execute periodically.

Parameters:
  • spacing (float/int) – how often to run the decorated function (required)
  • run_immediately (boolean) – option to specify whether to run immediately or wait until the spacing provided has elapsed before running for the first time

Miscellaneous

class futurist.ExecutorStatistics(failures=0, executed=0, runtime=0.0, cancelled=0)

Holds immutable information about a executors executions.

average_runtime

The average runtime of all submissions executed.

Returns:average runtime of all submissions executed
Return type:number
Raises:ZeroDivisionError when no executions have occurred.
cancelled

How many submissions were cancelled before executing.

Returns:how many submissions were cancelled before executing
Return type:number
executed

How many submissions were executed (failed or not).

Returns:how many submissions were executed
Return type:number
failures

How many submissions ended up raising exceptions.

Returns:how many submissions ended up raising exceptions
Return type:number
runtime

Total runtime of all submissions executed (failed or not).

Returns:total runtime of all submissions executed
Return type:number

Waiters

futurist.waiters.wait_for_any(fs, timeout=None)

Wait for one (any) of the futures to complete.

Works correctly with both green and non-green futures (but not both together, since this can’t be guaranteed to avoid dead-lock due to how the waiting implementations are different when green threads are being used).

Returns pair (done futures, not done futures).

futurist.waiters.wait_for_all(fs, timeout=None)

Wait for all of the futures to complete.

Works correctly with both green and non-green futures (but not both together, since this can’t be guaranteed to avoid dead-lock due to how the waiting implementations are different when green threads are being used).

Returns pair (done futures, not done futures).

class futurist.waiters.DoneAndNotDoneFutures(done, not_done)

Named tuple returned from wait_for* calls.