How do I wait for a data export to finish?

Submit an export job once, then ask for its status at growing intervals until it is complete or failed, and give up when the next wait would pass a deadline.

After this lesson, you can submit a trade-data export once, check its status at growing intervals, and return its file name or stop with a reason.

How do I check an export until it is ready?

wait_for asks for the export’s status with its id, returns the file name once the status is complete, and otherwise waits before the next check, with each wait 1.5 times the last up to a cap. An export of one day of XYZ’s trades that needs four checks is ready after waits of 0.05, 0.075 and 0.1125 seconds, 0.2375 seconds in all.

Asking for the status of the same job again and again is called polling. The simulated provider counts down a set number of checks per job and returns pending until the count reaches zero, then complete with a file name or failed with a message. The demo clock adds each wait to a counter in place of sleeping, so the times are the same on every run, and clock=time uses the real clock. The deadline is the total time budget in seconds, and a check that would start after it raises a TimeoutError. A live status request also needs its own timeout, as in the lesson on web APIs.

Code: the simulated provider and clock
class ExportService:
    def __init__(self):
        self.jobs = {}

    def submit(self, request, checks_needed, fails=False):
        job_id = f"job-{len(self.jobs) + 1}"
        self.jobs[job_id] = {"left": checks_needed, "fails": fails, "request": request}
        return job_id

    def status(self, job_id):
        job = self.jobs[job_id]
        job["left"] -= 1
        if job["left"] > 0:
            return {"state": "pending"}
        if job["fails"]:
            return {"state": "failed", "message": "no data for the requested dates"}
        return {"state": "complete", "file": f"{job_id}.csv.gz"}


class DemoClock:
    def __init__(self):
        self.seconds = 0.0

    def monotonic(self):
        return self.seconds

    def sleep(self, seconds):
        self.seconds += seconds

The following box defines wait_for and polls one export.

import time

def wait_for(service, job_id, first_wait=0.05, max_wait=0.2, deadline=1.0, clock=time):
    end = clock.monotonic() + deadline
    wait = min(first_wait, max_wait)
    checks = 0
    while True:
        result = service.status(job_id)
        checks += 1
        if result["state"] == "complete":
            return result["file"], checks
        if result["state"] == "failed":
            raise RuntimeError(f"{job_id} failed: {result['message']}")
        if clock.monotonic() + wait > end:
            raise TimeoutError(f"{job_id} still pending after {checks} checks")
        clock.sleep(wait)
        wait = min(wait * 1.5, max_wait)

service = ExportService()
clock = DemoClock()
job = service.submit({"ticker": "XYZ", "date": "2026-03-09"}, checks_needed=4)
print(wait_for(service, job, clock=clock), round(clock.seconds, 4))
('job-1.csv.gz', 4) 0.2375

How do I tell a failed export from a slow one?

A failed export raises a RuntimeError with the provider’s message, so the code stops checking at once, and a slow export raises a TimeoutError when the next wait would pass the deadline. An export of Saturday 7 March fails on its second check, and an export that needs 50 checks gives up after 7 checks and 0.80625 seconds, because one more wait of 0.2 would end at 1.00625 seconds, past the deadline of one second.

A slow export may still finish, so its id is worth keeping for a later check. except (RuntimeError, TimeoutError) catches both errors in one line.

The following box polls both exports and prints each error and the time spent.

failed_job = service.submit({"ticker": "XYZ", "date": "2026-03-07"}, checks_needed=2, fails=True)
slow_job = service.submit({"ticker": "XYZ", "date": "2026-03-09"}, checks_needed=50)
for job in [failed_job, slow_job]:
    start = clock.monotonic()
    try:
        wait_for(service, job, clock=clock)
    except (RuntimeError, TimeoutError) as error:
        print(type(error).__name__, error, round(clock.monotonic() - start, 5))
RuntimeError job-2 failed: no data for the requested dates 0.05
TimeoutError job-3 still pending after 7 checks 0.80625

Your turn

With a fresh ExportService, export XYZ’s trades for 9, 10 and 11 March 2026, each ready on its third check, and print each date beside its file name. You should see job-1.csv.gz to job-3.csv.gz.

Each pass submits one date and polls it.

exports = ExportService()
for day in ["2026-03-09", "2026-03-10", "2026-03-11"]:
    file_name, checks = wait_for(exports, exports.submit({"ticker": "XYZ", "date": day}, checks_needed=3), clock=clock)
    print(day, file_name)
2026-03-09 job-1.csv.gz
2026-03-10 job-2.csv.gz
2026-03-11 job-3.csv.gz