Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

How to Schedule Tasks Based on Current Time in Python

Use monotonic timers for delays and aware datetimes plus a calendar scheduler for real-world clock times. Here’s how to choose the right Python approach.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the scheduler by the kind of time you mean: use sched or an asyncio timer for an in-process delay, and a calendar-aware scheduler such as APScheduler 3.x for a one-time wall-clock run or recurring schedule. For real clock times, use an aware datetime with UTC or a named time zone; a wall-clock timestamp is not interchangeable with asyncio’s monotonic timer clock.

Choose the right Python scheduling approach

Need Approach Clock and lifecycle
A small event queue inside one process sched.scheduler Defaults to a monotonic clock; events run in the scheduling process and the queue can fall behind if an action takes too long. Python sched documentation
A delayed callback in an asyncio application loop.call_later(delay, callback) Delay is measured against the event loop’s monotonic clock; the returned handle can be cancelled. Python asyncio event-loop documentation
A callback at an event-loop deadline loop.call_at(when, callback) when must use the same reference as loop.time(), not Unix epoch seconds or a datetime. Python asyncio event-loop documentation
A one-time or recurring calendar job APScheduler 3.x date, interval, or cron trigger Choose the trigger for a one-off run, fixed elapsed interval, or selected wall-clock times. APScheduler 3.x user guide
A recurring calendar schedule that should survive restarts APScheduler 3.x with a persistent job store Configure stable job IDs during initialization and decide how missed executions should be handled. APScheduler 3.x user guide

First decide whether you need an elapsed delay or a civil clock time such as 9 a.m.; then decide whether the task repeats, whether it runs inside asyncio, and whether it must persist through process restarts. These choices determine both the API and the failure behavior to plan for.

Schedule a simple delay with sched

The standard-library scheduler is useful for a small queue owned by a running Python process. Its default time function is time.monotonic, which measures elapsed time rather than expressing a calendar date.

import sched
import time

scheduler = sched.scheduler(time.monotonic, time.sleep)

def do_work():
    print("running")

scheduler.enter(10, priority=1, action=do_work)
scheduler.run()

enter() schedules the action after a relative delay—in this example, ten seconds after it is entered. enterabs() instead accepts an absolute value in the scheduler’s configured clock reference. Both methods return an event object that can be cancelled. If an action takes longer than the available time, the scheduler falls behind rather than dropping queued events. Python sched documentation

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Schedule a delayed callback in asyncio

Use call_later() when an asyncio application needs a callback after a delay. It schedules the callback on the running event loop without blocking the loop with a sleep.

import asyncio

async def main():
    loop = asyncio.get_running_loop()
    handle = loop.call_later(10, print, "running")
    # Call handle.cancel() before it runs to cancel the callback.
    await asyncio.sleep(11)

asyncio.run(main())

For a deadline expressed on the event loop’s own clock, calculate it from loop.time() and pass that value to call_at():

loop = asyncio.get_running_loop()
when = loop.time() + 10
loop.call_at(when, callback)

call_at() does not accept a Unix timestamp or a datetime. The event loop uses a monotonic clock to track time, and timer callbacks may run up to one clock-resolution early, so this is not a hard real-time guarantee. Python asyncio event-loop documentation

Represent current time and target times safely

Use aware datetimes when a moment on the global timeline or a named civil time matters. Python recommends datetime.now(timezone.utc) for current UTC time; zoneinfo.ZoneInfo represents named IANA time zones such as a user’s location.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

now_utc = datetime.now(timezone.utc)
now_in_new_york = datetime.now(ZoneInfo("America/New_York"))

Naive datetimes do not identify a time zone, and datetime methods can interpret them as local time. Avoid assuming that an unspecified datetime means UTC. A named zone is preferable to hard-coding the current offset because governments can change time-zone rules, and the IANA database is periodically updated. Python datetime documentation

For a one-time target, define its time zone first, compare aware datetimes in that zone, and account for a target that is already in the past. You can then calculate delay = (target - now).total_seconds() and pass the delay to an in-process timer. That timer only lives in the current process; use persistent scheduling or an external job service if the job must remain scheduled through restarts.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose recurrence and missed-run behavior deliberately

One run, fixed intervals, or wall-clock times

APScheduler 3.x provides a date trigger for a one-time run, an interval trigger for fixed elapsed intervals, and a cron trigger for selected times such as 9 a.m. daily. Choose a scheduler suited to the application runtime; its guide includes AsyncIOScheduler for asyncio applications. These statements apply to APScheduler 3.x, not automatically to later major versions. APScheduler 3.x user guide

“Every 24 hours” and “every day at 9:00 local time” are different schedules. The first is an elapsed interval; the second follows civil wall time in a named zone. Daylight-saving transitions can make a local time disappear or occur twice, so a cron job may run less or more often than expected. APScheduler’s 3.x cron guidance recommends UTC or avoiding transition times when that variability is unacceptable. APScheduler 3.x cron trigger documentation

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Persistence, restarts, and missed executions

An in-process timer can be interrupted by a process exit, crash, deployment, or host sleep; it is not a durable queue. If jobs must survive restarts, use a persistent job store or an external scheduler. For APScheduler 3.x persistent jobs added during application initialization, give each job an explicit stable ID and use replace_existing=True to avoid adding another copy on each restart. APScheduler 3.x user guide

Decide what should happen if the application was down when a run was due: execute it within a grace period, skip it after a cutoff, or coalesce multiple missed executions into one. APScheduler 3.x exposes misfire grace-time and coalescing behavior; the right policy depends on whether delayed work remains useful and whether repeating missed work would be harmful. APScheduler 3.x user guide

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.