polling2: Enhanced Polling Utility

0.5.0 · active · verified Sat Apr 11

polling2 is an updated Python polling utility that provides many configurable options for retrying operations. It allows users to repeatedly call a function until a desired condition is met, handling timeouts, delays, and error logging. The current version is 0.5.0, with new features and minor fixes released periodically.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `polling2.poll` to wait for a simulated resource to become available. It sets a target function, a polling interval (`step`), a maximum wait time (`timeout`), and a `check_success` function to define when polling should stop. It also includes error handling for `TimeoutException`.

import time
from polling2 import poll, TimeoutException

# Simulate a resource that becomes available after some time
data_ready = False
def get_data():
    global data_ready
    if not data_ready:
        print("Data not ready yet...")
        return None
    print("Data is ready!")
    return {"status": "success", "data": [1, 2, 3]}

def check_data_status(result):
    return result is not None and result.get("status") == "success"

# Simulate data becoming ready after 2 seconds in a separate thread
import threading
def make_data_ready_soon():
    global data_ready
    time.sleep(2.5)
    data_ready = True

print("Attempting to poll for data...")
threading.Thread(target=make_data_ready_soon).start()

try:
    # Poll for the data, checking every 0.5 seconds, with a 5-second timeout
    result = poll(
        target=get_data,
        step=0.5,
        timeout=5,
        check_success=check_data_status,
        # log_errors=True # Uncomment to log errors from target function
    )
    print(f"Polling successful: {result}")
except TimeoutException:
    print("Polling timed out: Data did not become ready within 5 seconds.")
except Exception as e:
    print(f"An unexpected error occurred during polling: {e}")

view raw JSON →