systemd 定时任务实战复盘:把 crontab 的活搬成 timer
一句话:用一天时间把"print.service + print.timer 到点打印一行"跑通, 顺手踩完了 timer 在真实环境里最常见的 7 个坑:状态机语义、AccuracySec、daemon-reload、 手动触发、[Unit]/[Service] 段归属、SELinux 执行上下文、日志归因。 1. 环境 项 值 主机 node1 / node1.itcast.cn,192.168.88.128(ens160,VMware 虚机) 系统 CentOS Stream 9,内核 5.14.0-745.el9.x86_64,systemd 252-78.el9 资源 3.5G 内存 / 根分区 17G(36%)/ 时区 Asia/Hong_Kong (+0800) 登录 ssh root@192.168.88.128(WSL 公钥已写入 authorized_keys,免密;密码仅首次使用(已略)) SELinux Permissive(全程未改动) 任务 每天 15:20 由 timer 触发 service,往 /var/log/print.log 追加一行 hello world <时间> 最终文件 /usr/local/bin/print.sh(标签 bin_t,755): #!/bin/bash LOG=/var/log/print.log echo "hello world $(date '+%F %T')">>$LOG 2>&1 /etc/systemd/system/print.service: [Unit] Description=timed task [Service] Type=oneshot ExecStart=/usr/local/bin/print.sh [Install] WantedBy=multi-user.target /etc/systemd/system/print.timer: ...