温馨提示×

ubuntu定时器怎样启用

小樊
45
2026-10-21 13:54:11
栏目: 智能运维

在 Ubuntu 中,“定时器”通常有两种常见理解:系统级定时任务(cron / systemd timer) 和 用户级定时任务。下面分别说明如何启用和使用。


一、使用 cron(最常用)

1. 启用 cron 服务

Ubuntu 一般默认已安装并启用 cron。

sudo systemctl enable cron
sudo systemctl start cron

查看状态:

systemctl status cron

2. 编辑定时任务

当前用户:

crontab -e

root 用户:

sudo crontab -e

3. 示例(每天 3 点执行)

0 3 * * * /home/user/backup.sh

4. 查看已有任务

crontab -l

二、使用 systemd timer(更现代)

1. 创建 service

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

内容:

[Unit]
Description=My Task

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

2. 创建 timer

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

内容:

[Unit]
Description=Run My Task Daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

3. 启用定时器

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

4. 查看状态

systemctl list-timers

三、桌面环境定时(可选)

如果是 Ubuntu 桌面版,也可以用:

  • GNOME 扩展(如 Task Scheduler)
  • at 命令(一次性任务)
sudo apt install at
echo "sh /home/user/a.sh" | at 23:00

如果你能告诉我:

  • 是 服务器还是桌面
  • 想 定时执行什么
  • 是 开机启动还是周期执行

我可以给你更精确的配置示例。

0 踩