futurist(1)

FUTURIST(1) futurist FUTURIST(1)

NAME

futurist - futurist 3.2.1

Code from the future, delivered to you in the now.

USING FUTURIST

Features

Async

  • A futurist.GreenThreadPoolExecutor using eventlet green thread pools. It provides a standard executor API/interface and it also gathers execution statistics. It returns instances of futurist.GreenFuture objects.
  • A futurist.ProcessPoolExecutor derivative that gathers execution statistics. It returns instances of futurist.Future objects.
  • A futurist.SynchronousExecutor that doesn't run concurrently. It has the same executor API/interface and it also gathers execution statistics. It returns instances of futurist.Future objects.
  • A futurist.ThreadPoolExecutor derivative that gathers execution statistics. It returns instances of futurist.Future objects.

Periodics

A futurist.periodics.PeriodicWorker that can use the previously mentioned executors to run asynchronous work periodically in parallel or synchronously. It does this by executing arbitrary functions/methods that have been decorated with the futurist.periodics.periodic() decorator according to a internally maintained schedule (which itself is based on the heap algorithm).

Examples

Creating and using a synchronous executor

# NOTE: enable printing timestamp for additional data
import sys
import futurist
import eventlet
def delayed_func():

print("started")
eventlet.sleep(3)
print("done") #print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) e = futurist.SynchronousExecutor() fut = e.submit(delayed_func) eventlet.sleep(1) print("Hello") eventlet.sleep(1) e.shutdown() #print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))


Expected output:

started
done
Hello


Creating and using a green thread-based executor

# NOTE: enable printing timestamp for additional data
import sys
import futurist
import eventlet
def delayed_func():

print("started")
eventlet.sleep(3)
print("done") #print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) e = futurist.GreenThreadPoolExecutor() fut = e.submit(delayed_func) eventlet.sleep(1) print("Hello") eventlet.sleep(1) e.shutdown() #print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))


Expected output:

started
Hello
done


Creating and using a thread-based executor

import time
import futurist
def delayed_func():

time.sleep(0.1)
return "hello" e = futurist.ThreadPoolExecutor() fut = e.submit(delayed_func) print(fut.result()) e.shutdown()


Expected output:

hello


Creating and using a process-based executor

import time
import futurist
def delayed_func():

time.sleep(0.1)
return "hello" e = futurist.ProcessPoolExecutor() fut = e.submit(delayed_func) print(fut.result()) e.shutdown()


Expected output:

hello


Running a set of functions periodically

import futurist
from futurist import periodics
import time
import threading
@periodics.periodic(1)
def every_one(started_at):

print("1: %s" % (time.time() - started_at)) @periodics.periodic(2) def every_two(started_at):
print("2: %s" % (time.time() - started_at)) @periodics.periodic(4) def every_four(started_at):
print("4: %s" % (time.time() - started_at)) @periodics.periodic(6) def every_six(started_at):
print("6: %s" % (time.time() - started_at)) started_at = time.time() callables = [
# The function to run + any automatically provided positional and
# keyword arguments to provide to it everytime it is activated.
(every_one, (started_at,), {}),
(every_two, (started_at,), {}),
(every_four, (started_at,), {}),
(every_six, (started_at,), {}), ] w = periodics.PeriodicWorker(callables) # In this example we will run the periodic functions using a thread, it # is also possible to just call the w.start() method directly if you do # not mind blocking up the current program. t = threading.Thread(target=w.start) t.daemon = True t.start() # Run for 10 seconds and then stop. while (time.time() - started_at) <= 10:
time.sleep(0.1) w.stop() w.wait() t.join()


Running a set of functions periodically (using an executor)

import futurist
from futurist import periodics
import time
import threading
@periodics.periodic(1)
def every_one(started_at):

print("1: %s" % (time.time() - started_at))
time.sleep(0.5) @periodics.periodic(2) def every_two(started_at):
print("2: %s" % (time.time() - started_at))
time.sleep(1) @periodics.periodic(4) def every_four(started_at):
print("4: %s" % (time.time() - started_at))
time.sleep(2) @periodics.periodic(6) def every_six(started_at):
print("6: %s" % (time.time() - started_at))
time.sleep(3) started_at = time.time() callables = [
# The function to run + any automatically provided positional and
# keyword arguments to provide to it everytime it is activated.
(every_one, (started_at,), {}),
(every_two, (started_at,), {}),
(every_four, (started_at,), {}),
(every_six, (started_at,), {}), ] # To avoid getting blocked up by slow periodic functions we can also # provide a executor pool to make sure that slow functions only block # up a thread (or green thread), instead of blocking other periodic # functions that need to be scheduled to run. executor_factory = lambda: futurist.ThreadPoolExecutor(max_workers=2) w = periodics.PeriodicWorker(callables, executor_factory=executor_factory) # In this example we will run the periodic functions using a thread, it # is also possible to just call the w.start() method directly if you do # not mind blocking up the current program. t = threading.Thread(target=w.start) t.daemon = True t.start() # Run for 10 seconds and then stop. while (time.time() - started_at) <= 10:
time.sleep(0.1) w.stop() w.wait() t.join()


Stopping periodic function to run again (using NeverAgain exception)

import futurist
from futurist import periodics
import time
import threading
@periodics.periodic(1)
def run_only_once(started_at):

print("1: %s" % (time.time() - started_at))
raise periodics.NeverAgain("No need to run again after first run !!") @periodics.periodic(1) def keep_running(started_at):
print("2: %s" % (time.time() - started_at)) started_at = time.time() callables = [
# The function to run + any automatically provided positional and
# keyword arguments to provide to it everytime it is activated.
(run_only_once, (started_at,), {}),
(keep_running, (started_at,), {}), ] w = periodics.PeriodicWorker(callables) # In this example we will run the periodic functions using a thread, it # is also possible to just call the w.start() method directly if you do # not mind blocking up the current program. t = threading.Thread(target=w.start) t.daemon = True t.start() # Run for 10 seconds and then stop. while (time.time() - started_at) <= 10:
time.sleep(0.1) w.stop() w.wait() t.join()


Auto stopping the periodic worker when no more periodic work exists

import futurist
from futurist import periodics
import time
import threading
@periodics.periodic(1)
def run_only_once(started_at):

print("1: %s" % (time.time() - started_at))
raise periodics.NeverAgain("No need to run again after first run !!") @periodics.periodic(2) def run_for_some_time(started_at):
print("2: %s" % (time.time() - started_at))
if (time.time() - started_at) > 5:
raise periodics.NeverAgain("No need to run again !!") started_at = time.time() callables = [
# The function to run + any automatically provided positional and
# keyword arguments to provide to it everytime it is activated.
(run_only_once, (started_at,), {}),
(run_for_some_time, (started_at,), {}), ] w = periodics.PeriodicWorker(callables) # In this example we will run the periodic functions using a thread, it # is also possible to just call the w.start() method directly if you do # not mind blocking up the current program. t = threading.Thread(target=w.start, kwargs={'auto_stop_when_empty': True}) t.daemon = True t.start() # Run for 10 seconds and then check to find out that it had # already stooped. while (time.time() - started_at) <= 10:
time.sleep(0.1) print(w.pformat()) t.join()


CHANGES

3.2.1

Fix `shutdown(wait=True)` to wait for queued tasks

3.2.0

  • Use consistent validation error message for worker args
  • Remove sleeps from DynamicThreadPoolExecutor tests
  • Add DynamicThreadPoolExecutor that resizes itself
  • Fix ThreadWorker.stop to stop only this worker
  • Provide insights into the state of ThreadPoolExecutor
  • Trivial: avoid noqa in __init__.py
  • add pyproject.toml to support pip 23.1
  • Drop explicit dependency on python-subunit
  • tox: Remove basepython

3.1.1

3.1.0

  • deprecate eventlet based classes (green executors)
  • Remove fallback logic for Python < 3.3
  • Remove Python 3.8 support
  • Run pyupgrade to clean up Python 2 syntaxes
  • Use pre-commit hook to run doc8
  • pre-commit: Bump versions
  • Declare Python 3.12 support
  • Replace use of testtools.testcase.TestSkipped
  • Remove old excludes
  • reno: Update master for unmaintained/victoria

3.0.0

  • Bump hacking
  • Update python classifier in setup.cfg
  • coveragerc: Remove non-existent path
  • Revert "Moves supported python runtimes from version 3.8 to 3.10"
  • Moves supported python runtimes from version 3.8 to 3.10
  • tox: Replace whitelist_externals
  • Drop python3.6/3.7 support in testing runtime

2.4.1

  • tox: Trivial cleanups
  • trivial: Remove unnecessary 'coding' lines
  • Remove pbr from requirements.txt
  • Remove six
  • Add py39 package metadata
  • Update CI to use unversioned jobs template

2.4.0

  • remove unicode from code
  • setup.cfg: Replace dashes with underscores
  • trivial: Bump hacking to 4.x
  • Move flake8 as a pre-commit local target
  • Remove lower-constraints remnants
  • Use TOX_CONSTRAINTS_FILE
  • Uncap PrettyTable
  • Use py3 as the default runtime for tox
  • pre-commit: Lower flake8 version
  • Dropping lower constraints testing
  • ignore reno generated artifacts
  • Adding pre-commit
  • Add Python3 wallaby unit tests
  • Update master for stable/victoria

2.3.0

  • [goal] Migrate testing to ubuntu focal
  • drop mock from lower-constraints

2.2.0

  • Switch to newer openstackdocstheme and reno versions
  • Remove translation sections from setup.cfg
  • Remove monotonic usage
  • Bump default tox env from py37 to py38
  • Add py38 package metadata
  • Use unittest.mock instead of third party mock
  • Add Python3 victoria unit tests
  • Update master for stable/ussuri

2.1.1

  • Update hacking for Python3
  • Remove unnecessary blockquote in release notes

2.1.0

Make PrettyTable optional

2.0.0

[ussuri][goal] Drop python 2.7 support and testing

1.10.0

  • Fix Calling waiters.wait_for_any() blocks if future has called Condition.wait()
  • Switch to Ussuri jobs
  • Bump the openstackdocstheme extension to 1.20
  • Sync Sphinx requirement
  • Add release notes link to README
  • Update the constraints url
  • Update master for stable/train

1.9.0

  • Add Python 3 Train unit tests
  • Use opendev repository
  • OpenDev Migration Patch
  • Dropping the py35 testing
  • Update master for stable/stein

1.8.1

  • Use template for lower-constraints
  • Change openstack-dev to openstack-discuss

1.8.0

  • Only install monotonic on python2
  • Don't quote {posargs} in tox.ini
  • Remove the duplicated word
  • add lib-forward-testing-python3 test job
  • add python 3.6 unit test job
  • import zuul job settings from project-config
  • Update reno for stable/rocky
  • Switch to stestr
  • Follow the new PTI for document build
  • Add blueprints notes link to README
  • fix tox python3 overrides
  • Trivial: Update pypi url to new url

1.7.0

  • clean up test job configuration
  • set default python to python3
  • fix lower constraints and uncap eventlet
  • Update links in README
  • add lower-constraints job
  • Updated from global requirements
  • Update reno for stable/queens
  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements

1.6.0

Improve get optimal count of max_worker for pool

1.5.0

  • Avoid tox_install.sh for constraints support
  • Remove setting of version/release from releasenotes
  • Updated from global requirements
  • Updated from global requirements

1.4.0

  • Updated from global requirements
  • Updated from global requirements
  • Update reno for stable/pike
  • Updated from global requirements

1.3.0

  • Update URLs in documents according to document migration
  • Improve doctest and doc8 test
  • turn on warning-is-error in doc build
  • Update .gitignore
  • Improving cover and docs testenv
  • rearrange existing documentation to fit the new standard layout
  • Switch from oslosphinx to openstackdocstheme

1.2.0

  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements

1.1.0

  • Updated from global requirements
  • Expose underlying timeout error

1.0.0

Do not check spacing if periodic disabled

0.23.0

The python 3.4 support is removed

0.22.0

  • Updated from global requirements
  • Updated from global requirements
  • Typo fix: arbitary => arbitrary
  • Remove link to modindex
  • Introducing NeverAgain functionality for periodics
  • Update reno for stable/ocata
  • Add re-raising SystemExit exception

0.21.0

  • Removes unnecessary utf-8 coding
  • Add Constraints support
  • Show team and repo badges on README

0.20.0

  • replace _callables by _works
  • Updated from global requirements
  • Updated from global requirements
  • Add reno for release notes management
  • Updated from global requirements

0.19.0

  • Updated from global requirements
  • Updated from global requirements
  • Update homepage with developer documentation page

0.18.0

Eliminate unneccessary patching in GreenFuture

0.17.0

Remove discover from test-requirements

0.16.0

  • Remove 'smart' idleness check
  • Add Python 3.5 classifier and venv

0.15.0

  • Don't include openstack/common in flake8 exclude list
  • Updated from global requirements
  • Begin adding our own thread pool executor
  • Add what the watcher watches to the watcher as a property

0.14.0

  • Updated from global requirements
  • Fix 'on_failure' param not be used
  • Use prettytable to show pretty schedule/active/planned time table
  • Fix time related check in rejection test
  • Reduce/remove duplication in run functions
  • Fix jitter strategies

0.13.0

  • Single quote the callables name (when submission errors)
  • Updated from global requirements
  • Reschedule failed periodic tasks after a short delay
  • Fix wrong comparison in reject_when_reached

0.12.0

  • Updated from global requirements
  • Ensure all futures have completed before run returns

0.11.0

  • Updated from global requirements
  • Allow PeriodicWorker to skip executor shutdown in case of a preexisting executor

0.10.0

  • Expose underlying futures.CancelledError
  • Updated from global requirements
  • Updated from global requirements
  • Modification of the example code
  • PeriodicWorker.create to accept arguments for periodic tasks
  • Handle exceptions from executor.submit in PeriodicWorker
  • Add periodics.is_periodic to check if object is a periodic task
  • py26/py33 are no longer supported by Infra's CI

0.9.0

  • Updated from global requirements
  • Allow for providing different run work sync functions

0.8.0

Have the executor stats object repr look like the watcher repr

0.7.0

  • Add useful watcher '__repr__' function
  • Some minor refactoring and comment/note addition
  • Remove tests output from code coverage
  • No need for Oslo Incubator Sync
  • Move most of green helper classes -> '_green.py'

0.6.0

  • Add 'enabled' parameter to @periodic decorator
  • docs - Set pbr warnerrors option for doc build
  • Remove dummy/placeholder 'ChangeLog' as its not needed
  • Enhance the README
  • Remove green worker reference to its executor
  • Change ignore-errors to ignore_errors
  • Updated from global requirements
  • Activate pep8 check that _ is imported
  • Handle the case where 0.199 is provided as runtime
  • Just use a deque vs reverse pushing/popping
  • Ensure new entry in immediates gets processed during wait(s)

0.5.0

Updated from global requirements

0.4.0

  • Updated from global requirements
  • Updated from global requirements
  • Provide a thread differentiation attribute on executors

0.3.0

  • Updated from global requirements
  • Allow providing a callback to certain executors to reject new work
  • Disallow running 'start' twice
  • Allow for providing custom 'on_failure' callbacks
  • Delegate failure capturing to a object that is returned on run

0.2.0

  • Move doc8 to being a normal test requirement in test-requirements.txt
  • Ensure doctesting and doc8 testing done in py27 env
  • Updated from global requirements

0.1.2

  • Add future waiting helper module
  • Remove 3.3 & 2.6 classifier
  • Ensure we check callback '_is_periodic' on add
  • Add tests for the other basic strategies
  • Add a 'aligned last finished' strategy
  • Updated from global requirements
  • Move the periodic '_get_callback_name' to '_utils'
  • Add badge support to README.rst
  • Add periodics to doc features section

0.1.1

Ensure universal wheels are built

0.1.0

  • Updated from global requirements
  • Allow adding periodic callables at runtime
  • Show a prettier callback name
  • Allow providing customized scheduling strategies
  • Add history.rst that uses generated 'ChangeLog' file
  • Updated from global requirements
  • Add some basic periodic worker activation examples
  • Use monotonic lib. to avoid finding monotonic time function
  • Allow providing customized event + condition classes/factories
  • Allow providing a executor to be able to run in parallel
  • Add a periodics module that runs functions periodically
  • Add basic doctest(ed) executor examples
  • Allow synchronous executors to run in green compat. mode
  • Add some basic tests to ensure executors work
  • Attempt to use the monotonic pypi module if it's installed
  • Capital letters for futurist in HACKING.rst
  • Vastly improve the docs
  • Put features into the README.rst
  • Remove dependency on oslo.utils (replace with small util code)
  • Rename futures.py -> _futures.py and expose at futurist module
  • Updated from global requirements
  • Add initial .gitreview file and cookie-cutter template
  • Use the ability to save the exception traceback with newer futures
  • Rename utils to _utils
  • Add something to the README.rst
  • Fix missing comma
  • Add base files to get something working
  • Initial commit

API REFERENCE

Executors

class futurist.GreenThreadPoolExecutor(max_workers=1000, check_and_reject=None)
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...

__init__(max_workers=1000, check_and_reject=None)
Initializes a green thread pool executor.
Parameters
  • max_workers (int) -- maximum number of workers that can be simulatenously active at the same time, further submitted work will be queued up when this limit is reached.
  • check_and_reject (callback) -- a callback function that will be provided two position arguments, the first argument will be this executor instance, and the second will be the number of currently queued work items in this executors backlog; the callback should raise a RejectedSubmission exception if it wants to have this submission rejected.



property alive
Accessor to determine if the executor is alive/active.

shutdown(wait=True)
Clean-up the resources associated with the Executor.

It is safe to call this method several times. Otherwise, no other methods can be called after this one.

Parameters
  • wait -- If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.
  • cancel_futures -- If True then shutdown will cancel all pending futures. Futures that are completed or running will not be cancelled.



property 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

__init__(max_workers=None)
Initializes a new ProcessPoolExecutor instance.
Parameters
  • max_workers -- The maximum number of processes that can be used to execute the given calls. If None or not given then as many worker processes will be created as the machine has processors.
  • mp_context -- A multiprocessing context to launch the workers created using the multiprocessing.get_context('start method') API. This object should provide SimpleQueue, Queue and Process.
  • initializer -- A callable used to initialize worker processes.
  • initargs -- A tuple of arguments to pass to the initializer.
  • max_tasks_per_child -- The maximum number of tasks a worker process can complete before it will exit and be replaced with a fresh worker process. The default of None means worker process will live as long as the executor. Requires a non-'fork' mp_context start method. When given, we default to using 'spawn' if no mp_context is supplied.



property alive
Accessor to determine if the executor is alive/active.

property statistics
ExecutorStatistics about the executors executions.

submit(fn, *args, **kwargs)
Submit some work to be executed (and gather statistics).


class futurist.SynchronousExecutor(green=False, run_work_func=<function SynchronousExecutor.<lambda>>)
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, run_work_func=<function SynchronousExecutor.<lambda>>)
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)
  • run_work_func -- callable that takes a single work item and runs it (typically in a blocking manner)
  • run_work_func -- callable



property 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.


shutdown(wait=True)
Clean-up the resources associated with the Executor.

It is safe to call this method several times. Otherwise, no other methods can be called after this one.

Parameters
  • wait -- If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.
  • cancel_futures -- If True then shutdown will cancel all pending futures. Futures that are completed or running will not be cancelled.



property 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, check_and_reject=None)
Executor that uses a thread pool to execute calls asynchronously.

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

Note that this executor never shrinks its thread pool, which will cause the pool to eventually reach its maximum capacity defined by max_workers. Check DynamicThreadPoolExecutor for an alternative.

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

__init__(max_workers=None, check_and_reject=None)
Initializes a thread pool executor.
Parameters
  • max_workers (int) -- maximum number of workers that can be simultaneously active at the same time, further submitted work will be queued up when this limit is reached.
  • check_and_reject (callback) -- a callback function that will be provided two position arguments, the first argument will be this executor instance, and the second will be the number of currently queued work items in this executors backlog; the callback should raise a RejectedSubmission exception if it wants to have this submission rejected.



property alive
Accessor to determine if the executor is alive/active.

get_num_idle_workers()
Get the number of currently idle threads.

A thread is idle if it's waiting for new tasks from the queue.

This method is required to obtain the shutdown lock it provides an accurate count.


property num_workers
The current number of worker threads.

property queue_size
The current size of the queue.

This value represents the number of tasks that are waiting for a free worker thread.


shutdown(wait=True)
Clean-up the resources associated with the Executor.

It is safe to call this method several times. Otherwise, no other methods can be called after this one.

Parameters
  • wait -- If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.
  • cancel_futures -- If True then shutdown will cancel all pending futures. Futures that are completed or running will not be cancelled.



property statistics
ExecutorStatistics about the executors executions.

submit(fn, *args, **kwargs)
Submit some work to be executed (and gather statistics).


class futurist.DynamicThreadPoolExecutor(max_workers=None, check_and_reject=None, min_workers=1, grow_threshold=0.8, shrink_threshold=0.4)
Executor that creates or removes threads on demand.

As new work is scheduled on the executor, it will try to keep the proportion of busy threads within the provided range (between 40% and 80% by default). A busy thread is a thread that is not waiting on the task queue.

Each time a task is submitted, the executor makes a decision whether to grow or shrink the pool. It takes the proportion of the number of busy threads to the total number of threads and compares it to shrink_threshold and grow_threshold.

Initially, the pool is empty, so submitting a task always result in one new thread. Since min_workers must be greater than zero, at least one thread will always be available after this point.

Once the proportion of busy threads reaches grow_threshold (e.g. 4 out of 5 with the default grow_threshold of 0.8), a new thread is created when a task is submitted. If on submitting a task a proportion of busy threads is below shrink_threshold (e.g. only 2 out of 5), one idle thread is stopped.

The values of grow_threshold and shrink_threshold are different to prevent the number of threads from oscilating on reaching grow_threshold.

If threads are not created often in your application, the number of idle threads may stay high for a long time. To avoid it, you can call maintain() periodically to keep the number of threads within the thresholds.

__init__(max_workers=None, check_and_reject=None, min_workers=1, grow_threshold=0.8, shrink_threshold=0.4)
Initializes a thread pool executor.
Parameters
  • max_workers (int) -- maximum number of workers that can be simultaneously active at the same time, further submitted work will be queued up when this limit is reached.
  • check_and_reject (callback) -- a callback function that will be provided two position arguments, the first argument will be this executor instance, and the second will be the number of currently queued work items in this executors backlog; the callback should raise a RejectedSubmission exception if it wants to have this submission rejected.
  • min_workers -- the minimum number of workers that can be reached when shrinking the pool. Note that the pool always starts at zero workers and will be smaller than min_workers until enough workers are created. At least one thread is required.
  • grow_threshold (float) -- minimum proportion of busy threads to total threads for the pool to grow.
  • shrink_threshold (float) -- maximum proportion of busy threads to total threads for the pool to shrink.



maintain()
Keep the number of threads within the expected range.

If too many idle threads are running, they are deleted. Additionally, deleted workers are joined to free up resources.


shutdown(wait=True)
Clean-up the resources associated with the Executor.

It is safe to call this method several times. Otherwise, no other methods can be called after this one.

Parameters
  • wait -- If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.
  • cancel_futures -- If True then shutdown will cancel all pending futures. Futures that are completed or running will not be cancelled.




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.
Parameters
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 was cancelled.

done()
Return True if the future was cancelled or finished executing.

exception(timeout=None)
Return the exception raised by the call that the future represents.
Parameters
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.
Parameters
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_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=<class 'threading.Condition'>, event_cls=<class 'threading.Event'>, schedule_strategy='last_started', now_func=<built-in function monotonic>, on_failure=None)
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 = {'aligned_last_finished': (<function _aligned_last_finished_strategy>, <function _now_plus_periodicity>), 'aligned_last_finished_jitter': (<function _aligned_last_finished_strategy>, <function _now_plus_periodicity>), 'last_finished': (<function _last_finished_strategy>, <function _now_plus_periodicity>), 'last_finished_jitter': (<function _last_finished_strategy>, <function _now_plus_periodicity>), 'last_started': (<function _last_started_strategy>, <function _now_plus_periodicity>), 'last_started_jitter': (<function _last_started_strategy>, <function _now_plus_periodicity>)}
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=<class 'threading.Condition'>, event_cls=<class 'threading.Event'>, schedule_strategy='last_started', now_func=<built-in function monotonic>, on_failure=None)
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 (ExecutorFactory or any 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); preferably this is monotonically increasing
  • on_failure (callable) -- callable that will be called whenever a periodic function fails with an error, it will be provided four positional arguments and one keyword argument, the first positional argument being the callable that failed, the second being the type of activity under which it failed (IMMEDIATE or PERIODIC), the third being the spacing that the callable runs at and the fourth exc_info tuple of the failure. The keyword argument traceback will also be provided that may be be a string that caused the failure (this is required for executors which run out of process, as those can not currently transfer stack frames across process boundaries); if no callable is provided then a default failure logging function will be used instead (do note that any user provided callable should not raise exceptions on being called)



__len__()
How many callables/periodic work units are currently active.

add(cb, *args, **kwargs)
Adds a new periodic callback to the current worker.

Returns a Watcher if added successfully or the value None if not (or raises a ValueError if the callback is not correctly formed and/or decorated).

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=<class 'threading.Condition'>, event_cls=<class 'threading.Event'>, schedule_strategy='last_started', now_func=<built-in function monotonic>, on_failure=None, args=(), kwargs={})
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 (ExecutorFactory or any 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); preferably this is monotonically increasing
  • on_failure (callable) -- callable that will be called whenever a periodic function fails with an error, it will be provided four positional arguments and one keyword argument, the first positional argument being the callable that failed, the second being the type of activity under which it failed (IMMEDIATE or PERIODIC), the third being the spacing that the callable runs at and the fourth exc_info tuple of the failure. The keyword argument traceback will also be provided that may be be a string that caused the failure (this is required for executors which run out of process, as those can not currently transfer stack frames across process boundaries); if no callable is provided then a default failure logging function will be used instead (do note that any user provided callable should not raise exceptions on being called)
  • args (tuple) -- positional arguments to be passed to all callables
  • kwargs (dict) -- keyword arguments to be passed to all callables



iter_watchers()
Iterator/generator over all the currently maintained watchers.

reset()
Resets the workers internal state.

start(allow_empty=False, auto_stop_when_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)
  • auto_stop_when_empty (bool) -- when the provided periodic functions have all exited and this is false then the thread responsible for executing those methods will just spin/idle waiting for a new periodic function to be added; switching it to true will make this idling not happen (and instead when no more periodic work exists then the calling thread will just return).



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, enabled=True)
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
  • enabled (boolean) -- whether the task is enabled to run



class futurist.periodics.Watcher(metrics, work)
A read-only object representing a periodic callback's activities.
property average_elapsed
Avg. amount of time the periodic callback has ran for.

This may raise a ZeroDivisionError if there has been no runs.


property average_elapsed_waiting
Avg. amount of time the periodic callback has waited to run for.

This may raise a ZeroDivisionError if there has been no runs.


property elapsed
Total amount of time the periodic callback has ran for.

property elapsed_waiting
Total amount of time the periodic callback has waited to run for.

property failures
How many times the periodic callback ran unsuccessfully.

property requested_stop
If the work unit being ran has requested to be stopped.

property runs
How many times the periodic callback has been ran.

property successes
How many times the periodic callback ran successfully.

property work
Read-only named work tuple this object watches.


Miscellaneous

class futurist.ExecutorStatistics(failures=0, executed=0, runtime=0.0, cancelled=0)
Holds immutable information about a executors executions.
property 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.


property cancelled
How many submissions were cancelled before executing.
Returns
how many submissions were cancelled before executing
Return type
number


property executed
How many submissions were executed (failed or not).
Returns
how many submissions were executed
Return type
number


property failures
How many submissions ended up raising exceptions.
Returns
how many submissions ended up raising exceptions
Return type
number


property runtime
Total runtime of all submissions executed (failed or not).
Returns
total runtime of all submissions executed
Return type
number



Exceptions

class futurist.RejectedSubmission
Exception raised when a submitted call is rejected (for some reason).

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.

INSTALLATION

At the command line:

$ pip install futurist


Or, if you have virtualenvwrapper installed:

$ mkvirtualenv futurist
$ pip install futurist


CONTRIBUTING

If you would like to contribute to the development of OpenStack, you must follow the steps in this page:

http://docs.openstack.org/infra/manual/developers.html


If you already have a good understanding of how the system works and your OpenStack accounts are set up, you can skip to the development workflow section of this documentation to learn how changes to OpenStack should be submitted for review via the Gerrit tool:

http://docs.openstack.org/infra/manual/developers.html#development-workflow


Pull requests submitted through GitHub will be ignored.

Bugs should be filed on Launchpad, not GitHub:

https://bugs.launchpad.net/futurist


  • Index
  • Search Page

AUTHOR

Author name not set

COPYRIGHT

2013, OpenStack Foundation

October 24, 2025 3.2.1