Skip to main content

Throttler for asyncio Python that throttles to the next whole second

Project description

aio-throttle-to-next-second CircleCI Test Coverage

Throttler for asyncio Python that throttles to the next whole second, as reported by time.time(). This is useful to force an order on requests to a service that uses a "latest timestamp wins" strategy, such as S3.

Installation

pip install aio-throttle-to-next-second

Usage

Create a shared Throttler, with no arguments

from aio_throttle_to_next_second import Throttler

throttler = Throttler()

and then just before the piece(s) of code to be throttled, call this and await its result.

await throttler()
# Each execution reaching this line will reach this line at a different second

Example: multiple tasks throttled

import asyncio
import time

from aio_throttle_to_next_second import Throttler

async def main():
    throttler = Throttler()
    await asyncio.gather(*[
        worker(throttler) for _ in range(10)
    ])

async def worker(throttler):
    await throttler()
    # Each print will show a distinct second, though all workers started together
    print(int(time.time()))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

Example: single task throttled

import asyncio
import random
import time

from aio_throttle_to_next_second import Throttler

async def main():
    throttler = Throttler()
    for _ in range(10):
        await throttler()
        # Each print will show a distinct second, though there is a random sleep
        print(int(time.time()))
        await asyncio.sleep(random.random())

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

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

aio-throttle-to-next-second-0.0.1.tar.gz (2.3 kB view hashes)

Uploaded Source

Built Distribution

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