温馨提示×

ubuntu定时器如何启用服务

小樊
46
2026-10-09 23:30:45
栏目: 智能运维

在 Ubuntu 里“定时器启用服务”通常指 systemd 定时器(timer) 用来定时启动某个 service。下面按常见场景说明。


一、基本概念

  • service:真正执行任务的服务(如备份、脚本)
  • timer:定时器,决定什么时候启动对应的 service
  • 命名规则:
    xxx.timer 对应 xxx.service

二、创建一个 service(示例)

1. 创建 service 文件

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

内容示例:

[Unit]
Description=My Task Service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/mytask.sh

Type=oneshot 适合定时任务(执行完就退出)


三、创建对应的 timer

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

示例(每天 3:00 执行):

[Unit]
Description=Run My Task Daily

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
Unit=mytask.service

[Install]
WantedBy=timers.target

常见时间写法:

  • OnCalendar=Daily (每天)
  • OnCalendar=Hourly
  • OnCalendar=Mon *-*-* 09:00:00 (每周一 9 点)
  • OnBootSec=10min (开机 10 分钟后)

四、启用并启动定时器

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

说明:

  • enable:开机自启
  • --now:立即启动

五、查看与管理

查看所有定时器

systemctl list-timers

查看某个 timer 状态

systemctl status mytask.timer

手动触发一次

sudo systemctl start mytask.service

停止定时器

sudo systemctl stop mytask.timer
sudo systemctl disable mytask.timer

六、常见问题

1. 定时器没执行?

journalctl -u mytask.service
journalctl -u mytask.timer

2. 想用 crontab 而不是 systemd?

crontab -e
0 3 * * * /usr/local/bin/mytask.sh

但 Ubuntu 官方推荐 systemd timer。


如果你有:

  • 具体脚本
  • 想“开机运行”还是“周期运行”
  • 桌面版还是服务器版

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

0 踩