systemd timer 定时任务完全指南:从概念到每天 0 点实战

面向 Linux 运维岗的系统性学习材料,结合本机(WSL + AlmaLinux 9)实战编写。 这篇写了什么 四个小节,从概念到能跑:先讲 timer 是什么、和 cron 差在哪;再讲 service 与 timer 两个文件怎么配对;然后是 OnCalendar 时间表达式;最后从零做一个每天 0 点执行的任务,末尾附常见问题排查。 快速上手(30 秒版) 目标:每天 0 点打印一条信息 # 1. 写脚本 sudo tee /usr/local/bin/printit.sh >/dev/null <<'EOF' #!/bin/bash echo "定时任务执行啦!当前时间:$(date '+%F %T')" EOF sudo chmod +x /usr/local/bin/printit.sh # 2. 写 service 文件 sudo tee /etc/systemd/system/printit.service >/dev/null <<'EOF' [Unit] Description=每天打印任务 [Service] Type=oneshot ExecStart=/usr/local/bin/printit.sh EOF # 3. 写 timer 文件 sudo tee /etc/systemd/system/printit.timer >/dev/null <<'EOF' [Unit] Description=每天0点触发打印 [Timer] OnCalendar=daily Persistent=true [Install] WantedBy=timers.target EOF # 4. 启用 sudo systemctl daemon-reload sudo systemctl enable --now printit.timer # 5. 手动跑一次 + 看日志 sudo systemctl start printit.service sudo journalctl -u printit.service --since today 一句话原理 timer 只管什么时候触发 -> 到点启动同名 .service -> .service 里的 ExecStart 执行具体命令。 ...

September 29, 2026 · 3 分钟 · 565 字
本站访客 · 访问量