温馨提示×

ubuntu定时器怎样启动

小樊
36
2026-10-04 01:55:21
栏目: 智能运维

在 Ubuntu 中,“定时器”通常有以下几种常见场景。我分别说明 如何启动。


一、使用 systemd 定时器(推荐,类似 Windows 计划任务)

1. 创建 service 文件

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

内容示例:

[Unit]
Description=My Task

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

2. 创建 timer 文件

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

内容示例(每天 10:00 执行):

[Unit]
Description=Run My Task

[Timer]
OnCalendar=*-*-* 10:00:00
Persistent=true

[Install]
WantedBy=timers.target

3. 启动并开机自启

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

4. 查看状态

systemctl status mytask.timer
systemctl list-timers

✅ 这就是“启动 Ubuntu 定时器”的标准方式


二、使用 cron(传统方式)

1. 编辑当前用户的定时任务

crontab -e

2. 添加一行(每分钟执行)

* * * * * /home/user/test.sh

3. cron 服务启动

sudo systemctl enable --now cron

查看状态:

systemctl status cron

三、一次性定时任务(at)

sudo apt install at
sudo systemctl enable --now atd

echo "shutdown -h now" | at 23:00

总结

方式 启动命令
systemd timer systemctl enable --now xxx.timer
cron systemctl enable --now cron
at systemctl enable --now atd

如果你能告诉我 “你想定时做什么”,我可以帮你写完整配置。

0 踩