Skip to main content

A simpler way to handle timeouts in Python

Project description

EggTimer

There are some ubiquitous patterns that are elegant and simple. There are others that are not.

Common Solution

from time import time, sleep

max_sleep_time_sec = 1.5

start_time = time()
timeout_sec = 42.0

while time() - start_time < timeout_sec:
    # Do or check some stuff

    time_remaining = timeout_sec - (time() - start_time)
    if time_remaining > max_slep_time_sec:
        sleep(min(time_remaining, max_sleep_time_sec))
    else:
        sleep(max_sleep_time_sec)

What is the purpose of this loop? Oh, I see, it's a timeout. Is the order of operations correct in my loop condition? Have I correctly calculated time_remaining? Is my if clause correct? Hint: It's not. Does this code behave properly if the system clock is updated after I set start_time? Hint: It doesn't. How many times is this code duplicated within my application?

We can do better. EggTimer can help.

EggTimer Example

from time import sleep

from egg_timer import EggTimer

max_sleep_time_sec = 1.5

timer = EggTimer()
timer.set(42.0)

while not timer.is_expired():
    # Do or check some stuff

    sleep(min(timer.time_remaining_sec, max_sleep_time_sec))

Ah, that's better! Clear, concise, reusable, and expressive. The risk of defects is significantly lower, too!

Installation

Install with pip install -U egg-timer

Documentation

Classes

EggTimer - A class for checking whether or not a certain amount of time has elapsed.

ThreadSafeEggTimer - A thread-safe implementation of EggTimer.

See EggTimer Example for an example of how to use EggTime. ThreadSafeEggTimer shares the same interface.

Class documentation

Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from egg_timer import EggTimer
>>> help(EggTimer)
Help on class EggTimer in module egg_timer.egg_timer:

class EggTimer(builtins.object)
 |  A class for checking whether or not a certain amount of time has elapsed.
 |
 |  Methods defined here:
 |
 |  __init__(self)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  is_expired(self)
 |      Check whether or not the timer has expired
 |
 |      :return: True if the elapsed time since set(TIMEOUT_SEC) was called is greater than
 |               TIMEOUT_SEC, False otherwise
 |
 |  reset(self)
 |      Reset the timer without changing the timeout
 |
 |  set(self, timeout_sec: float)
 |      Set a timer
 |
 |      :param timeout_sec: A non-negative floating point number expressing the number of
 |                          seconds to set the timeout for.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |
 |  time_remaining_sec
 |      Return the amount of time remaining until the timer expires.
 |
 |      :return: The number of seconds until the timer expires. If the timer is expired, this
 |               function returns 0 (it will never return a negative number).
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)

>>>

Running the tests

Running the tests is as simple as poetry install && poetry run pytest

License

EggTimer is open-source software licensed under the GNU General Public License v3.0.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

egg_timer-1.2.0.tar.gz (16.5 kB view details)

Uploaded Source

Built Distribution

egg_timer-1.2.0-py3-none-any.whl (16.6 kB view details)

Uploaded Python 3

File details

Details for the file egg_timer-1.2.0.tar.gz.

File metadata

  • Download URL: egg_timer-1.2.0.tar.gz
  • Upload date:
  • Size: 16.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.0 CPython/3.10.6 Linux/5.15.0-58-generic

File hashes

Hashes for egg_timer-1.2.0.tar.gz
Algorithm Hash digest
SHA256 8e4155914ceb82c8b7248a0fdcdd0268fa841db5fd8666629dabed7fb937ab76
MD5 e876e8f29c7608f4fb889a7974ad3c01
BLAKE2b-256 e1095e46bc4d312b1acf94fff5f9c77d3e907e730766de1b5706e8c069d62951

See more details on using hashes here.

File details

Details for the file egg_timer-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: egg_timer-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 16.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.0 CPython/3.10.6 Linux/5.15.0-58-generic

File hashes

Hashes for egg_timer-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e476d57cca2ae85d502279ca0b8e84d1b47e241a56b888e18c944d780baf48db
MD5 17fc907ce0a5462d24d82395af1a4f0d
BLAKE2b-256 491f721c7dcffb54fac71fbdb87bd5c2bad3d015a5316e4dc62267f35d07c827

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page