在 Ubuntu 里“定时器”通常指两类东西,先说明一下,然后分别讲怎么配时间:
crontab -e
分 时 日 月 周 命令
示例:
0 2 * * * /home/user/backup.sh
含义:每天凌晨 2:00 执行
| 需求 | 配置 |
|---|---|
| 每分钟 | * * * * * |
| 每 5 分钟 | */5 * * * * |
| 每小时 | 0 * * * * |
| 每天 3:30 | 30 3 * * * |
| 每周一 9 点 | 0 9 * * 1 |
| 每月 1 号 | 0 0 1 * * |
crontab -l # 查看
crontab -r # 删除
sudo vim /etc/systemd/system/mytask.service
内容:
[Unit]
Description=My Task
[Service]
ExecStart=/usr/bin/bash /opt/mytask.sh
sudo vim /etc/systemd/system/mytask.timer
示例(每天 4:00):
[Unit]
Description=Run mytask daily
[Timer]
OnCalendar=*-*-* 04:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reexec
sudo systemctl enable --now mytask.timer
systemctl list-timers
sudo apt install at
echo "sh /opt/test.sh" | at 23:30
如果你能说清楚:
我可以直接给你一份可用的配置。