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.

Files for aio-throttle-to-next-second, version 0.0.1
Filename, size File type Python version Upload date Hashes
Filename, size aio_throttle_to_next_second-0.0.1-py3-none-any.whl (3.5 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size aio-throttle-to-next-second-0.0.1.tar.gz (2.3 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page