惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
爱范儿
爱范儿
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
罗磊的独立博客
D
Docker
美团技术团队
Recent Announcements
Recent Announcements
H
Hackread – Cybersecurity News, Data Breaches, AI and More
月光博客
月光博客
P
Proofpoint News Feed
博客园 - 聂微东
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
H
Help Net Security
T
Tailwind CSS Blog
S
Securelist
Google DeepMind News
Google DeepMind News
Scott Helme
Scott Helme
Jina AI
Jina AI
C
Cybersecurity and Infrastructure Security Agency CISA
Y
Y Combinator Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
博客园 - Franky
S
Security @ Cisco Blogs
C
CXSECURITY Database RSS Feed - CXSecurity.com
U
Unit 42
S
SegmentFault 最新的问题
Project Zero
Project Zero
P
Palo Alto Networks Blog
T
Threat Research - Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Full Disclosure
P
Privacy & Cybersecurity Law Blog
J
Java Code Geeks
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园_首页
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
M
MIT News - Artificial intelligence
NISL@THU
NISL@THU
Recent Commits to openclaw:main
Recent Commits to openclaw:main
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
Martin Fowler
Martin Fowler
V
Vulnerabilities – Threatpost
S
Schneier on Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Schedule Python Scripts with Cron: A Beginner's Complete Guide
German Yamil · 2026-05-08 · via DEV Community

How to Schedule Python Scripts with Cron: A Beginner's Complete Guide

The best automation script is one that runs itself.

Cron is the Unix scheduler built into every macOS and Linux machine. No SaaS, no cloud subscriptions, no third-party scheduler — just a text file that tells your system when to run your code.

Here's everything you need to use it correctly.


🎁 Free: AI Publishing Checklist — 7 steps in Python · Full pipeline: germy5.gumroad.com/l/xhxkzz (pay what you want, min $9.99)


The crontab syntax

┌─ minute       (0-59)
│  ┌─ hour      (0-23)
│  │  ┌─ day    (1-31)
│  │  │  ┌─ month  (1-12)
│  │  │  │  ┌─ weekday (0=Sun, 1=Mon ... 6=Sat)
│  │  │  │  │
*  *  *  *  *  command

Enter fullscreen mode Exit fullscreen mode

Common patterns:

# Every day at 10am
0 10 * * * python3 /path/to/script.py

# Every hour
0 * * * * python3 /path/to/script.py

# Every 15 minutes
*/15 * * * * python3 /path/to/script.py

# Every Monday at 9am
0 9 * * 1 python3 /path/to/script.py

# First of every month at midnight
0 0 1 * * python3 /path/to/script.py

Enter fullscreen mode Exit fullscreen mode

Use crontab.guru to verify any expression before running it.

Step 1: Open your crontab

crontab -e   # opens in your default editor
crontab -l   # list current jobs
crontab -r   # remove all jobs (careful!)

Enter fullscreen mode Exit fullscreen mode

If this is your first time, you'll be asked to choose an editor. Choose nano for simplicity.

Step 2: Write your script correctly

Before scheduling, your script needs two things:

1. Absolute paths — not relative:

# Wrong — cron runs from a different directory
with open("state.json") as f:    # FileNotFoundError at runtime
    data = json.load(f)

# Right — always resolve relative to the script itself
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATE_FILE = os.path.join(BASE_DIR, "state.json")

with open(STATE_FILE) as f:
    data = json.load(f)

Enter fullscreen mode Exit fullscreen mode

2. A shebang line so cron knows which Python to use:

#!/usr/bin/env python3
"""
publish_queue.py — publishes one article per day.
Cron: 0 10 * * * /usr/bin/python3 /Users/me/scripts/publish_queue.py
"""
import os, json, requests
# ...

Enter fullscreen mode Exit fullscreen mode

Step 3: Log everything

Cron jobs run silently. Without logging, you won't know if your script ran, crashed, or succeeded.

#!/usr/bin/env python3
import logging
import os
from datetime import datetime

# Log next to the script file
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_FILE = os.path.join(BASE_DIR, "publish.log")

logging.basicConfig(
    filename=LOG_FILE,
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger(__name__)

def main():
    log.info("Script started")
    try:
        # ... your actual work ...
        log.info("Published: My Article Title")
    except Exception as e:
        log.error(f"Failed: {e}", exc_info=True)
        raise

if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

Your crontab entry should also capture stdout/stderr:

0 10 * * * /usr/bin/python3 /Users/me/scripts/publish_queue.py >> /Users/me/scripts/publish.log 2>&1

Enter fullscreen mode Exit fullscreen mode

The >> file 2>&1 part appends both stdout and stderr to your log file.

Step 4: Environment variables

Cron runs with a minimal environment — none of your shell aliases, PATH entries, or exported variables are available.

The problem:

import os
token = os.environ["DEVTO_TOKEN"]  # KeyError — cron doesn't have this

Enter fullscreen mode Exit fullscreen mode

Solution 1: Use a .env file

# Load environment from a file at the top of your script
def load_env(path: str) -> None:
    """Load KEY=value pairs from a file into os.environ."""
    with open(path) as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                key, _, value = line.partition("=")
                os.environ[key.strip()] = value.strip().strip('"').strip("'")

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
load_env(os.path.join(BASE_DIR, ".env"))

token = os.environ["DEVTO_TOKEN"]  # works

Enter fullscreen mode Exit fullscreen mode

Your .env file:

DEVTO_TOKEN=abc123yourtoken
GUMROAD_TOKEN=xyz789yourtoken

Enter fullscreen mode Exit fullscreen mode

Solution 2: Set variables directly in crontab

# At the top of your crontab file
DEVTO_TOKEN=abc123yourtoken
GUMROAD_TOKEN=xyz789yourtoken

0 10 * * * python3 /path/to/publish_queue.py >> /path/to/publish.log 2>&1

Enter fullscreen mode Exit fullscreen mode

Step 5: Fix the PATH problem

Cron's PATH is usually just /usr/bin:/bin. Commands like python3 may not be found if you installed Python via Homebrew or pyenv.

The fix: use the full path to python3.

# Find your python3 path in terminal:
which python3
# /usr/local/bin/python3  (Homebrew)
# /opt/homebrew/bin/python3  (Apple Silicon Homebrew)
# /usr/bin/python3  (system Python)

# Then use that full path in crontab:
0 10 * * * /opt/homebrew/bin/python3 /Users/me/scripts/publish.py >> /Users/me/scripts/pub.log 2>&1

Enter fullscreen mode Exit fullscreen mode

Or set PATH explicitly at the top of your crontab:

PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin

0 10 * * * python3 /Users/me/scripts/publish.py >> /Users/me/scripts/pub.log 2>&1

Enter fullscreen mode Exit fullscreen mode

Step 6: Virtual environments

If your script uses third-party packages (requests, pillow, etc.), you need to point cron at your venv's Python:

# Create and activate venv (one time)
python3 -m venv /Users/me/scripts/.venv
source /Users/me/scripts/.venv/bin/activate
pip install requests pillow

# In crontab — use the venv python directly
0 10 * * * /Users/me/scripts/.venv/bin/python /Users/me/scripts/publish.py >> /Users/me/scripts/pub.log 2>&1

Enter fullscreen mode Exit fullscreen mode

No need to activate the venv in crontab — using the venv's python directly is equivalent.

Complete working example

The two cron jobs that power the publishing pipeline:

#!/usr/bin/env python3
"""
auto_publish_queue.py
Reads publish_queue.json and publishes the next pending article to Dev.to.

Cron: 0 10 * * * /path/to/.venv/bin/python /path/to/auto_publish_queue.py
"""
import os, json, re, logging, requests
from datetime import date

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
QUEUE_FILE = os.path.join(BASE_DIR, "publish_queue.json")
LOG_FILE = os.path.join(BASE_DIR, "queue.log")

logging.basicConfig(
    filename=LOG_FILE,
    level=logging.INFO,
    format="%(asctime)s %(message)s",
)
log = logging.getLogger(__name__)

TOKEN = os.environ.get("DEVTO_TOKEN", "")

def load_queue():
    with open(QUEUE_FILE) as f:
        return json.load(f)

def save_queue(q):
    with open(QUEUE_FILE, "w") as f:
        json.dump(q, f, indent=2)

def publish(filepath):
    with open(os.path.join(BASE_DIR, filepath)) as f:
        content = f.read()
    match = re.match(r'^---\n(.*?)\n---\n', content, re.DOTALL)
    fm = {}
    for line in match.group(1).splitlines():
        if line.startswith('tags: '):
            fm['tags'] = [t.strip() for t in line[6:].split(',')]
        elif ': ' in line:
            k, _, v = line.partition(': ')
            fm[k.strip()] = v.strip().strip('"')
    headers = {"api-key": TOKEN, "Content-Type": "application/json"}
    resp = requests.post("https://dev.to/api/articles", headers=headers, json={
        "article": {
            "title": fm["title"],
            "body_markdown": content,
            "published": True,
            "tags": fm.get("tags", []),
            "description": fm.get("description", ""),
        }
    })
    resp.raise_for_status()
    return resp.json()

def main():
    q = load_queue()
    if not q["pending"]:
        log.info("Queue empty — nothing to publish")
        return

    item = q["pending"][0]
    log.info(f"Publishing: {item['title']}")

    result = publish(item["filename"])
    url = f"https://dev.to{result['path']}"
    log.info(f"Published: {url}")

    q["pending"].pop(0)
    q["published"].append({
        "filename": item["filename"],
        "title": item["title"],
        "date": str(date.today()),
        "url": url,
        "id": result["id"],
    })
    save_queue(q)

if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

Crontab setup:

# Edit with: crontab -e
DEVTO_TOKEN=your_token_here

# 9am: ping RSS aggregators
0 9 * * * /path/to/.venv/bin/python /path/to/daily_ping.py >> /path/to/ping.log 2>&1

# 10am: publish next article from queue
0 10 * * * /path/to/.venv/bin/python /path/to/auto_publish_queue.py >> /path/to/queue.log 2>&1

Enter fullscreen mode Exit fullscreen mode

Debugging checklist

When a cron job doesn't run or fails silently:

# 1. Check if cron is running (macOS)
sudo launchctl list | grep cron

# 2. Check system cron log (macOS)
log show --predicate 'process == "cron"' --last 1h

# 3. Check your log file
tail -f /path/to/your/script.log

# 4. Test the exact command cron will run
/path/to/python3 /path/to/script.py >> /tmp/test.log 2>&1
cat /tmp/test.log

# 5. Check permissions
ls -la /path/to/script.py  # must be readable
chmod +x /path/to/script.py

Enter fullscreen mode Exit fullscreen mode

Common errors:

Error Cause Fix
Script never runs Cron daemon not running sudo launchctl load /System/Library/LaunchDaemons/com.vix.cron.plist
python3: not found PATH too minimal Use full path: /usr/bin/python3 or /opt/homebrew/bin/python3
ModuleNotFoundError Wrong Python (no venv) Use venv's Python: /path/.venv/bin/python
FileNotFoundError Relative path in script Use os.path.abspath(__file__) to build absolute paths
KeyError on env var Shell env not loaded Set vars at top of crontab or load from .env file

My two cron jobs publish one article per day and ping RSS aggregators — same pattern, different scripts: germy5.gumroad.com/l/xhxkzz — pay what you want, min $9.99.


Further Reading