温馨提示×

ubuntu定时器怎样编写

小樊
36
2026-09-25 07:59:44
栏目: 智能运维

在 Ubuntu 里“定时器”通常指 systemd timer(服务器/后台任务)或 cron(传统定时任务)。下面分别说明。


一、使用 systemd timer(推荐,功能强)

1. 创建 service 文件

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

内容示例:

[Unit]
Description=My Task

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

2. 创建 timer 文件

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

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

[Unit]
Description=Run mytask 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

二、使用 crontab(简单直观)

编辑当前用户定时任务

crontab -e

示例:

0 3 * * * /opt/mytask.sh

含义:

分 时 日 月 周
0  3  *  *  *

常用例子

*/5 * * * * command      # 每5分钟
0 0 * * * command        # 每天0点
0 9 * * 1 command        # 每周一9点

查看任务

crontab -l

三、一次性定时(at)

sudo apt install at
echo "/opt/mytask.sh" | at 03:00

四、选择建议

  • 后台服务/系统任务 → systemd timer
  • 简单脚本 → crontab
  • 一次性任务 → at

如果你有具体执行时间或脚本内容,我可以帮你直接写完整配置。

0 踩