Claude Code for schedule: Simple Python Job Scheduling — Claude Skills 360 Blog
Blog / AI / Claude Code for schedule: Simple Python Job Scheduling
AI

Claude Code for schedule: Simple Python Job Scheduling

Published: May 15, 2028
Read time: 5 min read
By: Claude Skills 360

schedule runs periodic jobs in Python. pip install schedule. Basic: import schedule; schedule.every(10).minutes.do(job). Interval: schedule.every(2).hours.do(job). Daily: schedule.every().day.at("09:30").do(job). Weekly: schedule.every().monday.at("08:00").do(job). Weekdays: schedule.every().monday.do(f); schedule.every().tuesday.do(f) (etc.). Args: schedule.every(5).minutes.do(job, "arg1", key="val"). Tag: schedule.every().hour.do(job).tag("reports","email"). Cancel tagged: schedule.clear("reports"). Cancel one: schedule.cancel_job(job). Next run: schedule.next_run(). All jobs: schedule.jobs. Idle seconds: schedule.idle_seconds(). Run loop: while True: schedule.run_pending(); time.sleep(1). Run all: schedule.run_all(). Custom scheduler: from schedule import Scheduler; s = Scheduler(). Multiple schedulers: separate Scheduler instances. Thread: threading.Thread(target=run_loop, daemon=True).start(). Until: schedule.every().hour.until("23:59").do(job). At: schedule.every().second.do(job) (minimum is 1 second). schedule.every(5).to(10).minutes.do(job) — random interval. Cancel if returns schedule.CancelJob. Claude Code generates schedule cron jobs, background loops, FastAPI startup schedulers, and taggable periodic task systems.

CLAUDE.md for schedule

## schedule Stack
- Version: schedule >= 1.2 | pip install schedule
- Interval: schedule.every(N).minutes/hours/days.do(fn, *args, **kwargs)
- Daily: schedule.every().day.at("HH:MM").do(fn)
- Loop: while True: schedule.run_pending(); time.sleep(1)
- Thread: threading.Thread(target=loop, daemon=True).start()
- Cancel: schedule.cancel_job(job) | schedule.clear("tag")

schedule Periodic Task Pipeline

# app/scheduler.py — schedule jobs, threading, tags, error handling, and FastAPI
from __future__ import annotations

import logging
import random
import threading
import time
from contextlib import contextmanager
from datetime import datetime, timedelta
from typing import Any, Callable

import schedule
from schedule import Job, Scheduler


log = logging.getLogger(__name__)


# ─────────────────────────────────────────────────────────────────────────────
# 1. Scheduler runner helpers
# ─────────────────────────────────────────────────────────────────────────────

def run_pending_loop(
    interval_secs: float = 1.0,
    stop_event: threading.Event | None = None,
    scheduler: Scheduler | None = None,
) -> None:
    """
    Blocking loop that calls run_pending() every interval_secs.
    Stops when stop_event is set (or KeyboardInterrupt).

    Usage (foreground):
        run_pending_loop()

    Usage (thread):
        stop = threading.Event()
        t = threading.Thread(target=run_pending_loop, args=(1.0, stop), daemon=True)
        t.start()
        ...
        stop.set()
    """
    s = scheduler or schedule.default_scheduler
    try:
        while not (stop_event and stop_event.is_set()):
            s.run_pending()
            # Sleep only as long as the next job needs — saves CPU
            idle = s.idle_seconds
            sleep_time = min(idle if idle else interval_secs, interval_secs)
            time.sleep(max(sleep_time, 0))
    except KeyboardInterrupt:
        pass


def start_background_scheduler(
    interval_secs: float = 1.0,
    scheduler: Scheduler | None = None,
) -> threading.Event:
    """
    Start scheduler in a daemon thread.
    Returns a threading.Event — set it to stop the loop cleanly.

    Usage:
        stop = start_background_scheduler()
        # ... application runs ...
        stop.set()
    """
    stop_event = threading.Event()
    t = threading.Thread(
        target=run_pending_loop,
        args=(interval_secs, stop_event, scheduler),
        daemon=True,
        name="schedule-worker",
    )
    t.start()
    log.info("Background scheduler started (thread: %s)", t.name)
    return stop_event


# ─────────────────────────────────────────────────────────────────────────────
# 2. Error-resilient job wrapper
# ─────────────────────────────────────────────────────────────────────────────

def safe_job(fn: Callable, *args: Any, reraise: bool = False, **kwargs: Any) -> Callable:
    """
    Wrap a function so that exceptions are logged but don't crash the scheduler.
    Returns a wrapper suitable for .do(safe_job(my_fn, arg1, key=val)).

    Usage:
        schedule.every().hour.do(safe_job(send_reports, "[email protected]"))
    """
    def wrapper() -> Any:
        try:
            return fn(*args, **kwargs)
        except Exception as e:
            log.error("Scheduled job '%s' failed: %s", fn.__name__, e, exc_info=True)
            if reraise:
                raise
    wrapper.__name__ = fn.__name__
    return wrapper


def cancellable_job(fn: Callable, *args: Any, **kwargs: Any) -> Callable:
    """
    Return a wrapper that calls fn and cancels itself if fn returns False or raises.

    Usage:
        # Job cancels itself after completing successfully once
        def one_shot_task():
            do_work()
            return schedule.CancelJob

        schedule.every().day.at("07:00").do(cancellable_job(one_shot_task))
    """
    def wrapper():
        result = fn(*args, **kwargs)
        if result is schedule.CancelJob or result is False:
            return schedule.CancelJob
    wrapper.__name__ = fn.__name__
    return wrapper


# ─────────────────────────────────────────────────────────────────────────────
# 3. Job factory helpers
# ─────────────────────────────────────────────────────────────────────────────

def add_interval_job(
    fn: Callable,
    *args: Any,
    every: int = 1,
    unit: str = "minutes",
    tag: str | None = None,
    safe: bool = True,
    scheduler: Scheduler | None = None,
    **kwargs: Any,
) -> Job:
    """
    Register a repeating interval job.
    unit: "seconds" | "minutes" | "hours" | "days" | "weeks"

    Example:
        add_interval_job(sync_users, every=30, unit="minutes", tag="sync")
    """
    s   = scheduler or schedule
    fn_ = safe_job(fn, *args, **kwargs) if safe else (lambda: fn(*args, **kwargs))
    job = getattr(getattr(s.every(every), unit), "do")(fn_)
    if tag:
        job.tag(tag)
    return job


def add_daily_job(
    fn: Callable,
    *args: Any,
    at: str = "00:00",
    tag: str | None = None,
    safe: bool = True,
    scheduler: Scheduler | None = None,
    **kwargs: Any,
) -> Job:
    """
    Register a daily job at a fixed time (HH:MM or HH:MM:SS).

    Example:
        add_daily_job(send_digest, "[email protected]", at="08:00", tag="email")
    """
    s   = scheduler or schedule
    fn_ = safe_job(fn, *args, **kwargs) if safe else (lambda: fn(*args, **kwargs))
    job = s.every().day.at(at).do(fn_)
    if tag:
        job.tag(tag)
    return job


def add_weekly_job(
    fn: Callable,
    *args: Any,
    day: str = "monday",
    at: str = "09:00",
    tag: str | None = None,
    safe: bool = True,
    scheduler: Scheduler | None = None,
    **kwargs: Any,
) -> Job:
    """
    Register a weekly job.
    day: "monday" | "tuesday" | ... | "sunday"

    Example:
        add_weekly_job(generate_weekly_report, at="06:00", day="monday", tag="reports")
    """
    s   = scheduler or schedule
    fn_ = safe_job(fn, *args, **kwargs) if safe else (lambda: fn(*args, **kwargs))
    job = getattr(s.every(), day).at(at).do(fn_)
    if tag:
        job.tag(tag)
    return job


def add_random_interval_job(
    fn: Callable,
    *args: Any,
    min_interval: int = 5,
    max_interval: int = 15,
    unit: str = "minutes",
    tag: str | None = None,
    safe: bool = True,
    scheduler: Scheduler | None = None,
    **kwargs: Any,
) -> Job:
    """
    Register a job with a randomised interval (e.g. 5–15 minutes).
    Useful for jitter to avoid thundering-herd problems.

    Example:
        add_random_interval_job(poll_external_api, min_interval=10, max_interval=20)
    """
    s   = scheduler or schedule
    fn_ = safe_job(fn, *args, **kwargs) if safe else (lambda: fn(*args, **kwargs))
    job = s.every(min_interval).to(max_interval)
    job = getattr(job, unit).do(fn_)
    if tag:
        job.tag(tag)
    return job


# ─────────────────────────────────────────────────────────────────────────────
# 4. Job inspection / management
# ─────────────────────────────────────────────────────────────────────────────

def list_jobs(scheduler: Scheduler | None = None) -> list[dict]:
    """Return a summary of all scheduled jobs."""
    s = scheduler or schedule.default_scheduler
    result = []
    for job in s.jobs:
        result.append({
            "next_run":  str(job.next_run),
            "last_run":  str(job.last_run),
            "interval":  str(job.interval),
            "unit":      job.unit,
            "tags":      list(job.tags),
            "job_func":  getattr(job.job_func, "__name__", str(job.job_func)),
        })
    return result


def cancel_by_tag(tag: str, scheduler: Scheduler | None = None) -> int:
    """Cancel all jobs with the given tag. Returns count cancelled."""
    s     = scheduler or schedule
    before = len((scheduler or schedule.default_scheduler).jobs)
    s.clear(tag)
    after  = len((scheduler or schedule.default_scheduler).jobs)
    return before - after


def next_run_in(scheduler: Scheduler | None = None) -> float | None:
    """Return seconds until next job fires, or None if no jobs."""
    s = scheduler or schedule.default_scheduler
    return s.idle_seconds


# ─────────────────────────────────────────────────────────────────────────────
# 5. Example periodic tasks
# ─────────────────────────────────────────────────────────────────────────────

def heartbeat(name: str = "default") -> None:
    """Emit a log heartbeat — useful for liveness monitoring."""
    log.info("[heartbeat] %s at %s", name, datetime.utcnow().isoformat())


def cleanup_temp_files(directory: str = "/tmp", max_age_hours: int = 24) -> int:
    """Simulate removing temp files older than max_age_hours. Returns count."""
    log.info("Cleaning up %s (files older than %dh)", directory, max_age_hours)
    return 0  # would return actual count in production


def send_daily_digest(recipients: list[str]) -> dict:
    """
    Simulate sending a daily digest email.
    Returns status per recipient.
    """
    log.info("Sending daily digest to %d recipients", len(recipients))
    return {r: "sent" for r in recipients}


def sync_database(source: str, destination: str) -> bool:
    """Simulate a database sync job."""
    log.info("Syncing %s%s", source, destination)
    return True


# ─────────────────────────────────────────────────────────────────────────────
# 6. FastAPI integration
# ─────────────────────────────────────────────────────────────────────────────

FASTAPI_EXAMPLE = '''
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.scheduler import (
    add_interval_job, add_daily_job, add_weekly_job,
    start_background_scheduler, list_jobs, cancel_by_tag,
    cleanup_temp_files, send_daily_digest, heartbeat,
)
import schedule

_stop_event = None

@asynccontextmanager
async def lifespan(app: FastAPI):
    global _stop_event
    # Register jobs
    add_interval_job(heartbeat, "api", every=1, unit="minutes", tag="monitoring")
    add_interval_job(cleanup_temp_files, "/tmp", 12, every=6, unit="hours", tag="maintenance")
    add_daily_job(send_daily_digest, ["[email protected]"], at="08:30", tag="email")
    add_weekly_job(lambda: None, day="sunday", at="02:00", tag="maintenance")

    _stop_event = start_background_scheduler()
    yield
    _stop_event.set()  # stop the scheduler thread

app = FastAPI(lifespan=lifespan)

@app.get("/scheduler/jobs")
def get_jobs():
    return {"jobs": list_jobs()}

@app.delete("/scheduler/jobs/{tag}")
def cancel_jobs(tag: str):
    count = cancel_by_tag(tag)
    return {"cancelled": count, "tag": tag}

@app.post("/scheduler/run-now/{tag}")
def run_tag_now(tag: str):
    schedule.run_all(delay_seconds=0)
    return {"status": "triggered", "tag": tag}
'''


# ─────────────────────────────────────────────────────────────────────────────
# Demo (sync mode — runs for a few seconds to show jobs firing)
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import schedule as sch

    # Use a fresh isolated scheduler for the demo
    s = Scheduler()

    print("=== Registering jobs ===")
    j1 = add_interval_job(heartbeat, "demo", every=2, unit="seconds", tag="demo", scheduler=s)
    j2 = add_interval_job(cleanup_temp_files, "/tmp", every=5, unit="seconds", tag="maint", scheduler=s)
    j3 = add_daily_job(send_daily_digest, ["[email protected]"], at="23:59", tag="email", scheduler=s)

    print(f"  {len(s.jobs)} jobs scheduled:")
    for j in list_jobs(s):
        print(f"    {j['job_func']}: every {j['interval']} {j['unit']} | next={j['next_run']}")

    print("\n=== Running for 6 seconds ===")
    stop = start_background_scheduler(scheduler=s)
    time.sleep(6)
    stop.set()

    print("\n=== Cancel maintenance jobs ===")
    cancelled = cancel_by_tag("maint", scheduler=s)
    print(f"  Cancelled {cancelled} jobs tagged 'maint'")
    print(f"  Remaining jobs: {len(s.jobs)}")

For the APScheduler alternative — APScheduler supports cron, interval, date triggers, multiple job stores (Redis, SQLAlchemy), and async schedulers via AsyncIOScheduler; schedule is a single-file zero-dependency library with a fluent API (every().monday.at("08:00").do(fn)) that is ideal for simple scripts and applications that don’t need persistence or distributed scheduling. For the Celery Beat alternative — Celery Beat provides production-grade periodic task scheduling with Redis/RabbitMQ brokers, task routing, and rate limiting as part of the full Celery ecosystem; schedule is the right choice when you want lightweight in-process scheduling without a broker, suitable for single-process web apps, CLI tools, and simple automation scripts. The Claude Skills 360 bundle includes schedule skill sets covering every().minutes/hours/days/weekday interval scheduling, at(“HH:MM”) time-based triggers, run_pending_loop() with idle_seconds sleep optimization, start_background_scheduler() daemon thread, safe_job() exception-resilient wrapper, cancellable_job() self-cancelling pattern, add_interval_job()/add_daily_job()/add_weekly_job() factory helpers, add_random_interval_job() for jitter, list_jobs()/cancel_by_tag() management, and FastAPI lifespan integration. Start with the free tier to try Python periodic job scheduling code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free