Skip to main content

Timed loops made simple

Project description


Build Status

I found myself re-implementing the same pattern over and over when it comes to repeating some task until some condition is met OR the time is up, so here it is abstracted and generalized into a neat package.

Yep, that's 25 lines of code + tests.

Here's a demo use case:

from timelooper import Looped, loop_timed
from datetime import timedelta

# Suppose we are listening to some queue
#   and want to batch the incoming messages.
#   However, we only want to wait for
#   some limited time for a batch 
#   to be formed.

class CollectableBatch(Looped):
    def __init__(self, queue, maxsize):
        self.batch = []
        self._queue = queue
        self._maxsize = maxsize
    async def do(self) -> None:
        self.batch.append(await self._queue.get())

    def should_stop(self) -> bool:
        return len(self.batch) == self._maxsize

collected = CollectableBatch(queue, maxsize=10)
await loop_timed(collected, timedelta(seconds=30))  

print(collected.batch)  # or whatever


pip install timelooper

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

timelooper-0.1.2.tar.gz (3.0 kB view hashes)

Uploaded Source

Built Distribution

timelooper-0.1.2-py3-none-any.whl (3.1 kB view hashes)

Uploaded Python 3

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