diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index d7a953023..45dad8a07 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1136,6 +1136,87 @@ class RepeatedTimer(threading.Thread): if callable(self.on_finish): self.on_finish() +class ResettableTimer(threading.Thread): + """ + This class represents an action that should be run after a specified amount of time. It is similar to python's + own :class:`threading.Timer` class, with the addition of being able to reset the counter to zero. + + ResettableTimers are started, as with threads, by calling their ``start()`` method. The timer can be stopped (in + between runs) by calling the :func:`cancel` method. Resetting the counter can be done with the :func:`reset` method. + + For example: + + .. code-block:: python + + def hello(): + print("Ran hello() at {}").format(time.time()) + + t = ResettableTimers(60.0, hello) + t.start() + print("Started at {}").format(time.time()) + time.sleep(30) + t.reset() + print("Reset at {}").format(time.time()) + + Arguments: + interval (float or callable): The interval before calling ``function``, in seconds. Can also be a callable + returning the interval to use, in case the interval is not static. + function (callable): The function to call. + args (list or tuple): The arguments for the ``function`` call. Defaults to an empty list. + kwargs (dict): The keyword arguments for the ``function`` call. Defaults to an empty dict. + on_cancelled (callable): Callback to call when the timer finishes due to being cancelled. + on_reset (callable): Callback to call when the timer is reset. + """ + + def __init__(self, interval, function, args=None, kwargs=None, on_reset=None, on_cancelled=None): + threading.Thread.__init__(self) + self._event = threading.Event() + self._mutex = threading.Lock() + self.is_reset = True + + if args is None: + args = [] + if kwargs is None: + kwargs = dict() + + self.interval = interval + self.function = function + self.args = args + self.kwargs = kwargs + self.on_cancelled = on_cancelled + self.on_reset = on_reset + + + def run(self): + while self.is_reset: + with self._mutex: + self.is_reset = False + self._event.wait(self.interval) + + if not self._event.isSet(): + self.function(*self.args, **self.kwargs) + with self._mutex: + self._event.set() + + def cancel(self): + with self._mutex: + self._event.set() + + if callable(self.on_cancelled): + self.on_cancelled() + + def reset(self, interval=None): + with self._mutex: + if interval: + self.interval = interval + + self.is_reset = True + self._event.set() + self._event.clear() + + if callable(self.on_reset): + self.on_reset() + class CountedEvent(object): diff --git a/tests/util/test_resettable_timer.py b/tests/util/test_resettable_timer.py new file mode 100644 index 000000000..1e227ad8b --- /dev/null +++ b/tests/util/test_resettable_timer.py @@ -0,0 +1,59 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import unittest +import mock +import time + +from octoprint.util import ResettableTimer + +class ResettableTimerTest(unittest.TestCase): + + def setUp(self): + pass + + def test_function(self): + timer_task = mock.MagicMock() + + timer = ResettableTimer(10, timer_task) + timer.start() + + # wait for it + timer.join() + + self.assertEqual(1, timer_task.call_count) + + def test_reset_callback(self): + timer_task = mock.MagicMock() + on_reset_cb = mock.MagicMock() + + timer = ResettableTimer(10, timer_task, on_reset=on_reset_cb) + timer.start() + + timer.reset() + + # wait for it + timer.join() + + self.assertEqual(1, timer_task.call_count) + self.assertEqual(1, on_reset_cb.call_count) + + def test_canceled_callback(self): + timer_task = mock.MagicMock() + on_cancelled_cb = mock.MagicMock() + + timer = ResettableTimer(10, timer_task, on_cancelled=on_cancelled_cb) + timer.start() + + time.sleep(5) + + timer.cancel() + + time.sleep(10) + + self.assertEqual(0, timer_task.call_count) + self.assertEqual(1, on_cancelled_cb.call_count)