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

推荐订阅源

GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
宝玉的分享
宝玉的分享
IT之家
IT之家
Recent Announcements
Recent Announcements
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
M
MIT News - Artificial intelligence
D
Docker
C
CERT Recently Published Vulnerability Notes
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Recorded Future
Recorded Future
博客园 - 司徒正美
D
DataBreaches.Net
Last Week in AI
Last Week in AI
U
Unit 42
人人都是产品经理
人人都是产品经理
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
量子位
大猫的无限游戏
大猫的无限游戏
博客园 - Franky
T
Tailwind CSS Blog
小众软件
小众软件
Y
Y Combinator Blog
WordPress大学
WordPress大学
B
Blog RSS Feed
C
Check Point Blog
H
Help Net Security
The Last Watchdog
The Last Watchdog
F
Full Disclosure
腾讯CDC
V
Visual Studio Blog
Google Online Security Blog
Google Online Security Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Troy Hunt's Blog
N
News and Events Feed by Topic
F
Fortinet All Blogs
B
Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
J
Java Code Geeks
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
有赞技术团队
有赞技术团队
博客园 - 三生石上(FineUI控件)
TaoSecurity Blog
TaoSecurity Blog
I
InfoQ
V
Vulnerabilities – Threatpost

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
Cron Not Working on Mac? How to Fix the macOS Sleep Trap with launchd
Arjun Adhikari · 2026-05-25 · via DEV Community

If you've ever built an automated script like a Python crypto price scraper, a daily backup script, or an RSS archiver, you probably felt like a genius right up until the moment it failed to run.

You set up your crontab perfectly. You told it to run every day at 6:30 PM. You tested the script in your terminal, and it worked flawlessly. But then you check your logs a few days later, and... crickets. Nothing happened.

What gives?

If you are running your automation on a personal Mac, you've just run into the classic Sleep Mode Trap.


Why Your Mac is Ignoring Your Cron Jobs

cron is a legendary piece of software. It has been the backbone of Unix automation for decades. But cron was designed for servers that live in cold, dark rooms and literally never go to sleep.

Your Mac is different. When you close the lid or walk away for an hour, your Mac goes to sleep to save battery.

Here is how cron handles sleep: It doesn't.

If you have a job scheduled for 6:30 PM and your laptop is asleep at 6:30 PM, cron simply shrugs and skips it. It won't try again until tomorrow at 6:30 PM. If your laptop is closed tomorrow at 6:30 PM too? Skipped again. Your "automated" pipeline is now completely broken unless you babysit it and keep your screen awake.


Apple knew this was a problem, which is why they built launchd.

launchd is the modern, macOS-native replacement for cron and init. It manages everything running in the background on your Mac. Unlike cron, launchd is generally much better at handling sleep/wake scenarios — it can run missed scheduled jobs shortly after wake, depending on your exact power state and configuration.

Cron vs. launchd at a Glance

Feature cron launchd
Handles sleep well
Native macOS support
Simple syntax
Good for servers
Good for personal laptops

LaunchAgents vs. LaunchDaemons: What's the Difference?

Before writing your configuration, it's crucial to know where to put it. launchd separates jobs into two categories:

  1. LaunchDaemons (/Library/LaunchDaemons/) — Run as the root system user as soon as the Mac boots, even before anyone logs in. Use this for system-level services like database servers or network listeners.
  2. LaunchAgents (~/Library/LaunchAgents/) — Run as your specific user account, only after you log in. Since personal scripts need access to your files, home directory, and user permissions, LaunchAgents are almost always what you want.

How launchd Actually Works Under the Hood

launchd is the absolute core of macOS. When you turn on your Mac, launchd is the very first process that starts — it has Process ID 1. Every other application on your Mac is technically a "child" of launchd.

When your Mac sleeps, the hardware clock keeps ticking. When you open your laptop, the Kernel updates the system time and launchd checks its internal schedule. If it missed a StartCalendarInterval job during the sleep window, it triggers the job shortly after wake to catch up.


Step-by-Step: Migrating from Cron to launchd

Instead of editing a crontab, you create a Property List (.plist) XML configuration file and drop it in ~/Library/LaunchAgents/.

Here is a complete, production-ready template for a Python script that runs Monday through Friday at 6:30 PM.

File: ~/Library/LaunchAgents/com.yourname.dailyscript.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>

    <!-- 1. Unique identifier for this job -->
    <key>Label</key>
    <string>com.yourname.dailyscript</string>

    <!-- 2. Command to run — always use absolute paths for the interpreter AND the script -->
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/python3</string>
        <string>/Users/yourname/projects/my_script.py</string>
    </array>

    <!-- 3. Working directory — prevents "file not found" errors inside your script -->
    <key>WorkingDirectory</key>
    <string>/Users/yourname/projects</string>

    <!-- 4. Environment variables — launchd starts with a minimal PATH, so declare it explicitly -->
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
    </dict>

    <!-- 5. Schedule: Monday (1) through Friday (5) at 18:30 -->
    <key>StartCalendarInterval</key>
    <array>
        <dict>
            <key>Weekday</key><integer>1</integer>
            <key>Hour</key><integer>18</integer>
            <key>Minute</key><integer>30</integer>
        </dict>
        <dict>
            <key>Weekday</key><integer>2</integer>
            <key>Hour</key><integer>18</integer>
            <key>Minute</key><integer>30</integer>
        </dict>
        <dict>
            <key>Weekday</key><integer>3</integer>
            <key>Hour</key><integer>18</integer>
            <key>Minute</key><integer>30</integer>
        </dict>
        <dict>
            <key>Weekday</key><integer>4</integer>
            <key>Hour</key><integer>18</integer>
            <key>Minute</key><integer>30</integer>
        </dict>
        <dict>
            <key>Weekday</key><integer>5</integer>
            <key>Hour</key><integer>18</integer>
            <key>Minute</key><integer>30</integer>
        </dict>
    </array>

    <!-- 6. Persistent log files — use ~/Library/Logs, NOT /tmp (which gets wiped by macOS) -->
    <key>StandardOutPath</key>
    <string>/Users/yourname/Library/Logs/dailyscript.out</string>
    <key>StandardErrorPath</key>
    <string>/Users/yourname/Library/Logs/dailyscript.err</string>

</dict>
</plist>

Understanding the Key Fields

Key What it does
Label Unique name used to identify and manage the job
ProgramArguments Exact command and arguments — equivalent to typing in your terminal
WorkingDirectory Sets the pwd inside your script; prevents relative path failures
EnvironmentVariables Injects env vars — critical because launchd starts with a barebones $PATH
StartCalendarInterval Defines the schedule; 0 and 7 are both Sunday
StandardOutPath Where print() and stdout output goes
StandardErrorPath Where errors and tracebacks go

Why ~/Library/Logs/ instead of /tmp/?
macOS periodically cleans /tmp/ — sometimes as frequently as on every reboot. If you put your logs there, you could lose them before you ever read them. ~/Library/Logs/ is the macOS convention for persistent, user-level logs.


Activating the Job (The Modern Way)

Historically, most tutorials teach launchctl load, but Apple considers this legacy. The modern, recommended way to register a LaunchAgent for your user session is:

# Register the job
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.yourname.dailyscript.plist

# To test it immediately without waiting for the scheduled time
launchctl start com.yourname.dailyscript

# If you edit the plist, you must unload and reload it
launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/com.yourname.dailyscript.plist
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.yourname.dailyscript.plist


Common launchd Gotchas

If your script isn't running, it is almost certainly one of these:

  1. Barebones $PATHlaunchd starts with a minimal environment. If your script calls python, node, or any Homebrew tool by name without a full path, it will silently fail. Always declare your PATH explicitly in EnvironmentVariables, and on Apple Silicon Macs include /opt/homebrew/bin.

  2. Absolute paths everywherelaunchd does not expand ~. Use /Users/yourname/ literally everywhere — in ProgramArguments, WorkingDirectory, and log paths.

  3. Scripts fail silently — There is no terminal window to show you errors. Always check your log files after the first run:

    cat ~/Library/Logs/dailyscript.err
    
  4. Verify the job is registered:

    launchctl list | grep com.yourname.dailyscript
    

    The three columns are: PID (blank if not running), last exit code (0 = success), and label.

  5. Stream live system logs for deeper debugging:

    log stream --predicate 'subsystem == "com.apple.launchd"'
    

A Quick Note on KeepAlive

As you explore launchd further, you will encounter <key>KeepAlive</key>. Setting it to <true/> tells launchd to treat your script as a permanent background daemon — if it crashes or exits, launchd will immediately restart it. This is exactly what you want for a persistent web server, but completely wrong for a daily scraper that is supposed to run once and exit.


What About Windows?

Windows has its own built-in equivalent: Task Scheduler.

To enable the same "catch-up on wake" behavior:

  1. Open Task Scheduler and create a new task.
  2. Set your trigger (daily, weekly, etc.).
  3. Go to the Settings tab.
  4. Check "Run task as soon as possible after a scheduled start is missed".

That single checkbox gives you the same sleep-safe behavior as launchd's StartCalendarInterval. Windows also supports environment variables and working directory settings under the task's Actions configuration.


Final Thoughts

cron is a classic for a reason — simple, powerful, and universal. But it was built for servers that never sleep. If you are building personal automation on a laptop, you owe it to yourself to use the scheduler your OS was actually designed around.

Your data (and your sanity) will thank you.