Add periodics.is_periodic to check if object is a periodic task

People implementing their own periodic tasks collection (as opposed
to using PeriodicWorker.create) need to know if something is
a periodic task without inspecting its private attributes.
This function returning True means something is safe to add
to a PeriodicWorker (will not raise ValueError).

Change-Id: Iee8da601b1bc994188c58ca459574a466270bf63
This commit is contained in:
Dmitry Tantsur 2016-01-06 17:14:49 +01:00 committed by Thomas Goirand
parent 977a07da46
commit c01db2de8e
2 changed files with 25 additions and 0 deletions

View File

@ -115,6 +115,16 @@ def _check_attrs(obj):
return missing_attrs
def is_periodic(obj):
"""Check whether an object is a valid periodic callable.
:param obj: object to inspect
:type obj: anything
:return: True if obj is a periodic task, otherwise False
"""
return callable(obj) and not _check_attrs(obj)
def periodic(spacing, run_immediately=False, enabled=True):
"""Tags a method/function as wanting/able to execute periodically.

View File

@ -234,6 +234,21 @@ class TestPeriodics(testscenarios.TestWithScenarios, base.TestCase):
self.assertIsNotNone(w.add(add_me))
self.assertEqual(1, len(w))
def test_is_periodic(self):
@periodics.periodic(0.5, enabled=False)
def no_add_me():
pass
@periodics.periodic(0.5)
def add_me():
pass
self.assertTrue(periodics.is_periodic(add_me))
self.assertTrue(periodics.is_periodic(no_add_me))
self.assertFalse(periodics.is_periodic(self.test_is_periodic))
self.assertFalse(periodics.is_periodic(42))
def test_watcher(self):
def cb():