Ubuntu中3种定时任务

cron # 最常用,周期性执行任务

systemd timer # 更现代,适合服务级定时任务

at # 只执行一次的定时任务

1. cron:周期性定时任务

cron 是一套定时任务系统。

你看到这些都属于 cron

复制代码
复制代码
crontab -e
crontab -l
sudo crontab -e
/etc/crontab
/etc/cron.daily/
/etc/cron.weekly/
/etc/cron.monthly/

典型写法:

复制代码
复制代码
* * * * * /bin/bash /usr/local/scripts/test.sh

例如:

复制代码
复制代码
0 2 * * * /bin/bash /usr/local/scripts/backup.sh

意思是:每天凌晨 2 点执行 backup.sh

所以这种格式:

复制代码
复制代码
分 时 日 月 周 命令

就是 cron 格式


2. systemd timer:systemd 的定时任务

systemd timer 是 systemd 提供的定时器机制。

它不是写在 crontab -e 里,而是写两个文件:

复制代码
复制代码
xxx.service
xxx.timer

例如:

复制代码
复制代码
/etc/systemd/system/backup.service
/etc/systemd/system/backup.timer

backup.service:定义要执行什么任务。

复制代码
复制代码
[Unit]
Description=Backup job

[Service]
Type=oneshot
ExecStart=/bin/bash /usr/local/scripts/backup.sh

backup.timer:定义什么时候执行。

复制代码
复制代码
[Unit]
Description=Run backup every day

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

[Install]
WantedBy=timers.target

启动 timer:

复制代码
复制代码
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer

查看 timer:

复制代码
复制代码
systemctl list-timers

所以看到这些命令,一般就是 systemd timer

复制代码
复制代码
systemctl list-timers
systemctl status xxx.timer
systemctl enable --now xxx.timer

3. at:一次性定时任务

at 只执行一次,不是周期性。

例如:

复制代码
复制代码
echo "touch /tmp/test.txt" | at now + 10 minutes

意思是:10 分钟后执行一次

查看一次性任务:

复制代码
复制代码
atq

删除一次性任务:

复制代码
复制代码
atrm 任务编号

分类表

类型 用途 配置位置 / 命令 是否周期执行
cron 最常用的周期任务 crontab -e/etc/crontab/etc/cron.daily/
systemd timer 服务级定时任务 xxx.service + xxx.timer 是,也可以一次
at 一次性任务 atatqatrm 否,只执行一次

最简单理解

复制代码
复制代码
cron = 写一行时间表达式,周期执行命令
systemd timer = 写 service + timer 两个配置文件,交给 systemd 管理
at = 指定未来某个时间,只执行一次

你刚开始学 Ubuntu 定时任务,重点掌握这个就行:

复制代码
复制代码
crontab -e

然后写:

复制代码
复制代码
0 2 * * * /bin/bash /usr/local/scripts/backup.sh >> /var/log/backup.log 2>&1

这个就是典型的 cron 定时任务

相关推荐
这个DBA有点耶1 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
DBA_G1 天前
从地面到云霄:GBase数据库在民航三大场景的落地实践
数据库
自由能燃气设备1 天前
商用全预混低氮冷凝锅炉免费方案vs付费方案对比+选型避坑指南
大数据·数据库·人工智能
科创致远1 天前
科创致远 ESOP 系统核心效能与实战价值展示
大数据·数据库·人工智能·精益工程
geovindu1 天前
sql: Transaction & Concurrency Patterns using postgresql 18
postgresql·数据库开发·数据库架构
2601_962218611 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法
张洛闻Eren1 天前
k8s云原生【第十课】:水平 Pod 自动扩缩容
运维·数据库·云原生·kubernetes·github
于平安1 天前
MySQL-触发器
数据库·mysql
白远山1 天前
上海24小时自助健身房解决方案实战指南与经验分享
java·数据库·架构·需求分析
Omics Pro1 天前
斯坦福Nature+Science|广义虚拟细胞基础大模型
数据库·人工智能·算法·机器学习·自然语言处理