From 1f4aeed76b4e8a0c4ff869418bcf5c313fb09c0b Mon Sep 17 00:00:00 2001 From: Dmitry Tantsur Date: Wed, 6 Jan 2016 17:06:52 +0100 Subject: [PATCH] PeriodicWorker.create to accept arguments for periodic tasks Sometimes it might be required to pass the same arguments to all tasks collected by create (e.g. ironic passes context). Change-Id: I7992c59e76b8b7b9101501d75cb7a53d982d07fd --- futurist/periodics.py | 11 ++++++----- futurist/tests/test_periodics.py | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/futurist/periodics.py b/futurist/periodics.py index 8fcdfb5..f6d889d 100644 --- a/futurist/periodics.py +++ b/futurist/periodics.py @@ -358,7 +358,7 @@ class PeriodicWorker(object): log=None, executor_factory=None, cond_cls=threading.Condition, event_cls=threading.Event, schedule_strategy='last_started', now_func=utils.now, - on_failure=None): + on_failure=None, args=_NO_OP_ARGS, kwargs=_NO_OP_KWARGS): """Automatically creates a worker by analyzing object(s) methods. Only picks up methods that have been tagged/decorated with @@ -415,6 +415,10 @@ class PeriodicWorker(object): any user provided callable should not raise exceptions on being called :type on_failure: callable + :param args: positional arguments to be passed to all callables + :type args: tuple + :param kwargs: keyword arguments to be passed to all callables + :type kwargs: dict """ callables = [] for obj in objects: @@ -424,10 +428,7 @@ class PeriodicWorker(object): if six.callable(member): missing_attrs = _check_attrs(member) if not missing_attrs: - # These do not support custom args, kwargs... - callables.append((member, - cls._NO_OP_ARGS, - cls._NO_OP_KWARGS)) + callables.append((member, args, kwargs)) return cls(callables, log=log, executor_factory=executor_factory, cond_cls=cond_cls, event_cls=event_cls, schedule_strategy=schedule_strategy, now_func=now_func, diff --git a/futurist/tests/test_periodics.py b/futurist/tests/test_periodics.py index 15d0e79..6556b1c 100644 --- a/futurist/tests/test_periodics.py +++ b/futurist/tests/test_periodics.py @@ -19,6 +19,7 @@ import time import eventlet from eventlet.green import threading as green_threading +import mock import testscenarios import futurist @@ -283,6 +284,26 @@ class TestPeriodics(testscenarios.TestWithScenarios, base.TestCase): am_called = sum(called) self.assertGreaterEqual(am_called, 4) + def test_create_with_arguments(self): + m = mock.Mock() + + class Object(object): + @periodics.periodic(0.5) + def func1(self, *args, **kwargs): + m(*args, **kwargs) + + executor_factory = lambda: self.executor_cls(**self.executor_kwargs) + w = periodics.PeriodicWorker.create(objects=[Object()], + executor_factory=executor_factory, + args=('foo',), + kwargs={'bar': 'baz'}, + **self.worker_kwargs) + with self.create_destroy(w.start): + self.sleep(2.0) + w.stop() + + m.assert_called_with('foo', bar='baz') + class RejectingExecutor(futurist.GreenThreadPoolExecutor): MAX_REJECTIONS_COUNT = 2