Poll until done
Wait on an async job by checking back periodically until it's done, or until you give up. Useful for Replicate predictions, OpenAI batch jobs, and Mux transcodes.
Use this to
- Poll a Replicate prediction until it returns succeeded, failed, or canceled
- Wait for an OpenAI batch job to finish, then process the output file
- Check a Mux asset every 30 seconds until it's ready to play or has errored
- Wait for any third-party async job (export, transcoding, model inference) until the result is ready
Code
Replicate: poll a prediction until terminal status
// after kicking off the prediction await dk.schedule("check-replicate", { key: prediction.id, delay: "2m", }); // handler reschedules itself until Replicate reports a terminal status. // Replicate's terminal set is succeeded, failed, canceled. dk.handle("check-replicate", async ({ key, reschedule }) => { const prediction = await replicate.predictions.get(key); if (["succeeded", "failed", "canceled"].includes(prediction.status)) { await onPredictionDone(prediction); return; } // give up after an hour, derived from the prediction's own state const elapsedMs = Date.now() - new Date(prediction.created_at).getTime(); if (elapsedMs > 60 * 60 * 1000) { await alerts.page("prediction-stuck", { id: key }); return; } reschedule({ delay: "2m" }); });
OpenAI batch: same shape, different terminal statuses
dk.handle("check-batch", async ({ key, reschedule }) => { const batch = await openai.batches.retrieve(key); if (["completed", "failed", "expired", "cancelled"].includes(batch.status)) { await onBatchDone(batch); return; } // batch jobs run for hours, so check less often than predictions reschedule({ delay: "5m" }); });
Mux: poll an asset until it's ready
dk.handle("check-asset", async ({ key, reschedule }) => { const asset = await mux.video.assets.retrieve(key); if (asset.status === "ready" || asset.status === "errored") { await onAssetReady(asset); return; } reschedule({ delay: "30s" }); });
npm install delaykit
bun add delaykit