温馨提示×

ubuntu定时器如何编写

小樊
48
2026-09-22 07:16:25
栏目: 智能运维

在 Ubuntu(以及其他 Linux 发行版)中,定时器一般有两种常见方式:

  1. cron —— 传统定时任务(按时间周期执行)
  2. systemd timer —— 系统级定时器(更现代,适合服务化任务)

下面分别说明。


一、使用 cron(最常用)

1. 编辑定时任务

crontab -e

如果是系统级任务:

sudo crontab -e

2. 基本格式

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

3. 示例

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

4. 查看任务

crontab -l

5. 日志查看

grep CRON /var/log/syslog

二、使用 systemd timer(推荐用于服务)

1. 创建 service 文件

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

内容示例:

[Unit]
Description=My Task

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

2. 创建 timer 文件

sudo vim /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-reexec
sudo systemctl enable --now mytask.timer

4. 查看状态

systemctl list-timers
systemctl status mytask.timer

三、该用哪种?

场景 推荐
简单脚本、个人任务 cron
系统服务、需要日志/依赖 systemd timer
容器/服务器管理 systemd timer

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

  • 是 用户级还是系统级
  • 想 多久执行一次
  • 执行的是 脚本 / 命令 / 程序

我可以直接帮你写完整配置。

0 踩