温馨提示×

ubuntu定时器怎么启用

小樊
43
2026-10-01 04:15:02
栏目: 智能运维

在 Ubuntu 中,“定时器”最常见的是 systemd 的 timer(推荐、服务器常用),也可以是传统的 cron。下面分别说明如何启用。


一、使用 systemd timer(推荐)

1. 创建一个 service 单元

例如 /etc/systemd/system/mytask.service:

[Unit]
Description=My Task

[Service]
Type=oneshot
ExecStart=/usr/bin/echo "hello from timer"

2. 创建一个 timer 单元

例如 /etc/systemd/system/mytask.timer:

[Unit]
Description=Run mytask 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
systemctl status mytask.timer

✅ 这样就启用了 systemd 定时器。


二、使用 cron(传统方式)

1. 编辑当前用户的 cron

crontab -e

2. 添加定时任务

例如每天凌晨 2 点执行:

0 2 * * * /path/to/script.sh

3. 确保 cron 服务运行

sudo systemctl enable --now cron

三、如何选择?

  • 服务器 / 系统级任务:用 systemd timer
  • 用户级简单任务:用 cron
  • 需要日志、依赖管理:用 systemd

如果你愿意,可以告诉我:

  • 是 用户级还是系统级
  • 多久执行一次
  • 执行什么命令

我可以直接帮你写好配置。

0 踩