Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Last active July 7, 2023 04:33
Show Gist options
  • Select an option

  • Save bbengfort/a7d46013f39cf367daa5 to your computer and use it in GitHub Desktop.

Select an option

Save bbengfort/a7d46013f39cf367daa5 to your computer and use it in GitHub Desktop.

Revisions

  1. bbengfort revised this gist Feb 3, 2016. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions interval.py
    Original file line number Diff line number Diff line change
    @@ -12,7 +12,7 @@ def __init__(self, interval, function, args=[], kwargs={}):
    self.running = False
    self._timer = None

    def _handle(self):
    def __call__(self):
    """
    Handler function for calling the partial and continuting.
    """
    @@ -29,7 +29,7 @@ def start(self):
    return

    # Create the timer object, start and set state.
    self._timer = Timer(self.interval, self._handle)
    self._timer = Timer(self.interval, self)
    self._timer.start()
    self.running = True

  2. bbengfort created this gist Feb 3, 2016.
    69 changes: 69 additions & 0 deletions interval.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    from threading import Timer
    from functools import partial

    class Interval(object):

    def __init__(self, interval, function, args=[], kwargs={}):
    """
    Runs the function at a specified interval with given arguments.
    """
    self.interval = interval
    self.function = partial(function, *args, **kwargs)
    self.running = False
    self._timer = None

    def _handle(self):
    """
    Handler function for calling the partial and continuting.
    """
    self.running = False # mark not running
    self.start() # reset the timer for the next go
    self.function() # call the partial function

    def start(self):
    """
    Starts the interval and lets it run.
    """
    if self.running:
    # Don't start if we're running!
    return

    # Create the timer object, start and set state.
    self._timer = Timer(self.interval, self._handle)
    self._timer.start()
    self.running = True

    def stop(self):
    """
    Cancel the interval (no more function calls).
    """
    if self._timer:
    self._timer.cancel()
    self.running = False
    self._timer = None


    if __name__ == "__main__":
    import time
    import random

    def clock(start):
    """
    Prints out the elapsed time when called from start.
    """
    print "elapsed: {:0.3f} seconds".format(
    time.time() - start
    )

    # Create an interval.
    interval = Interval(random.randint(1,3), clock, args=[time.time(),])
    print "Starting Interval, press CTRL+C to stop."
    interval.start()

    while True:
    try:
    time.sleep(0.1)
    except KeyboardInterrupt:
    print "Shutting down interval ..."
    interval.stop()
    break