温馨提示×

ubuntu定时器如何安装

小樊
43
2026-09-12 23:19:00
栏目: 智能运维

在 Ubuntu 里“定时器”通常有两种常见理解,我先分别说明,你按需选择:


一、使用 systemd 定时器(推荐,服务器/后台任务)

Ubuntu 默认使用 systemd,它自带定时功能,比 cron 更强大。

1. 创建 service 文件

sudo nano /etc/systemd/system/mytimer.service

内容示例:

[Unit]
Description=My Timer Task

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

2. 创建 timer 文件

sudo nano /etc/systemd/system/mytimer.timer

内容示例(每天 3 点执行):

[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 mytimer.timer

4. 查看状态

systemctl list-timers

二、使用 cron(传统定时任务)

1. 安装 cron

Ubuntu 一般已安装:

sudo apt update
sudo apt install cron

2. 启动 cron

sudo systemctl enable --now cron

3. 编辑定时任务

crontab -e

示例(每天 3 点执行脚本):

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

三、桌面图形化定时器(GUI)

如果你是 Ubuntu 桌面版:

  • 可用「任务计划(Task Scheduler)」或
  • 安装 gnome-schedule(旧版)

如果你能告诉我:

  • 是 服务器还是桌面
  • 想 定时执行什么

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

0 踩