温馨提示×

ubuntu定时器怎样设置

小樊
45
2026-09-19 05:10:37
栏目: 智能运维

在 Ubuntu 中,“定时器”通常有两种常见理解:一次性/周期性执行任务的定时计划(cron / at),以及 systemd 定时器(systemd timer)。下面分别介绍。


一、使用 cron(最常用)

1. 编辑当前用户的定时任务

crontab -e

2. 格式说明

* * * * * 命令
分 时 日 月 周

示例:

  • 每天 3:00 执行脚本
0 3 * * * /home/user/backup.sh
  • 每 5 分钟执行一次
*/5 * * * * /home/user/check.sh
  • 每周一 9:30
30 9 * * 1 /home/user/weekly.sh

3. 查看和删除

crontab -l      # 查看
crontab -r      # 删除

4. 系统级 cron

sudo nano /etc/crontab

或放入:

/etc/cron.d/
/etc/cron.daily/
/etc/cron.hourly/

二、使用 at(一次性定时)

1. 安装

sudo apt install at
sudo systemctl enable --now atd

2. 使用

at 23:00
> /home/user/backup.sh
> Ctrl+D

指定时间示例:

at now + 1 hour
at 2026-01-20 10:00

查看任务:

atq

删除任务:

atrm 任务编号

三、使用 systemd 定时器(更现代、可控)

1. 创建 service

sudo nano /etc/systemd/system/mytask.service

内容:

[Unit]
Description=My Task

[Service]
Type=oneshot
ExecStart=/home/user/mytask.sh

2. 创建 timer

sudo nano /etc/systemd/system/mytask.timer

内容(每天 3:00):

[Unit]
Description=Run My Task Daily

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target

3. 启用

sudo systemctl daemon-reload
sudo systemctl enable --now mytask.timer

4. 查看状态

systemctl list-timers
systemctl status mytask.timer

四、定时重启示例

sudo crontab -e
0 4 * * * /sbin/reboot

如果你能说明具体需求(例如:定时备份、定时重启、开机延迟执行、用户级还是系统级),我可以给你更精确的配置示例。

0