apscheduler
БесплатноБез исполняемых скриптовНе проверенAPScheduler is a Python library that runs functions on a schedule inside your own process, using cron expressions, fixed intervals or one-off dates, and can…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
APScheduler — schedule Python functions in-process
Overview
APScheduler (Advanced Python Scheduler) lets an application schedule its own functions: "every 15 minutes", "weekdays at 08:30", "once at this timestamp". The scheduler runs inside your Python process, either in a background thread, blocking the main thread, or on an asyncio event loop. Jobs can live in memory or in a database through a job store.
Version note: pip install apscheduler installs the 3.x line (3.11.3 at the time of writing, Python 3.8+). The 4.x line is a pre-release with a different API (Scheduler, AsyncScheduler, add_schedule, data stores); pip skips it unless asked with --pre. Everything below is the 3.x API. If a snippet imports apscheduler.schedulers.background it is 3.x; do not mix it with 4.x names.
Four building blocks to know:
- Trigger: when to run (
date,interval,cron, plus combining triggers). - Job store: where jobs are kept (
MemoryJobStoreby default,SQLAlchemyJobStore,MongoDBJobStore,RedisJobStore). - Executor: how jobs run (thread pool by default, process pool for CPU work, asyncio executor for coroutines).
- Scheduler: ties them together (
BackgroundScheduler,BlockingScheduler,AsyncIOScheduler).
Instructions
Installation
python3 -m venv .venv
.venv/bin/pip install apscheduler sqlalchemy
sqlalchemy is needed only for SQLAlchemyJobStore. Check what you got with .venv/bin/pip show apscheduler.
Choose the scheduler class
| Class | Use it when |
|---|---|
BlockingScheduler |
The scheduler is the whole program (a worker script run by systemd or a container). start() never returns. |
BackgroundScheduler |
The scheduler lives next to something else, such as a Flask app. start() returns at once. |
AsyncIOScheduler |
The app already runs an asyncio loop (FastAPI, aiohttp). |
Cron, interval and one-off jobs
from datetime import datetime, timedelta
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
def export_orders(region):
print(f"exporting orders for {region}")
sched = BlockingScheduler(timezone="Europe/Berlin")
# Every weekday at 08:30
sched.add_job(export_orders, CronTrigger(day_of_week="mon-fri", hour=8, minute=30),
args=["eu"], id="orders-eu", replace_existing=True)
# Same thing from a crontab string (five fields)
sched.add_job(export_orders, CronTrigger.from_crontab("0 2 * * *"),
args=["us"], id="orders-us", replace_existing=True)
# Every 15 minutes, starting 10 seconds from now
sched.add_job(export_orders, "interval", minutes=15,
start_date=datetime.now() + timedelta(seconds=10),
args=["apac"], id="orders-apac", replace_existing=True)
# Once
sched.add_job(export_orders, "date", run_date=datetime(2026, 12, 31, 23, 0),
args=["year-end"], id="orders-year-end", replace_existing=True)
sched.start() # blocks; Ctrl+C raises KeyboardInterrupt, so wrap in try/except if you need cleanup
Always give a job an explicit id and replace_existing=True. Without the id, a persistent store gets a new random id on every start, and each restart duplicates every job.
Keep jobs across restarts
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
sched = BackgroundScheduler(
jobstores={"default": SQLAlchemyJobStore(url="sqlite:///jobs.sqlite")},
timezone="Europe/Berlin",
)
sched.add_job("billing.jobs:send_invoices", "cron", hour=6, id="invoices", replace_existing=True)
sched.start()
Rules for persistent jobs, because the job is pickled into the database:
- The function must be importable at module top level (or given as a
"package.module:function"string). Lambdas, nested functions and bound methods of unpicklable objects are rejected. - Arguments must be picklable: pass ids and plain values, not database connections.
- When the code changes (new args, new trigger), re-add with
replace_existing=True. Stored jobs are not re-read from your source.
Control misfires, overlap and workers
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
sched = BackgroundScheduler(
executors={"default": ThreadPoolExecutor(10), "cpu": ProcessPoolExecutor(2)},
job_defaults={
"coalesce": True, # several missed runs collapse into one
"max_instances": 1, # never run the same job concurrently
"misfire_grace_time": 300, # still run if started up to 5 min late
},
)
sched.add_job(rebuild_report, "cron", hour=3, executor="cpu", id="report", replace_existing=True)
The process pool starts child processes that import your main module again. Put the scheduler setup under if __name__ == "__main__": and import rebuild_report from a regular module; with top-level setup code the pool breaks and the job
Установить apscheduler в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл apscheduler?
APScheduler is a Python library that runs functions on a schedule inside your own process, using cron expressions, fixed intervals or one-off dates, and can keep its jobs in a database so they survive restarts. Use when a user wants to "run a Python function every night", "replace crontab scripts", "schedule background jobs in Flask or FastAPI", "persist scheduled jobs in SQLite", or "stop missed runs from piling up". Covers the 3.x API that pip installs today.
Как установить скилл apscheduler?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл apscheduler запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic