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有点耶3 小时前
NULL不是空——数据库里最反直觉的设计,90%新人踩过的坑
数据库·mysql·代码规范
这个DBA有点耶5 小时前
AI写的SQL跑崩了生产库,这锅谁背?
数据库·人工智能·程序员
镜舟科技5 小时前
Databricks 再提 LTAP,AI 时代的数据底座为何重回大一统叙事?
数据库·架构·agent
Databend6 小时前
从湖仓升级为 Agent 时代的数据控制面,Snowflake 和 Databricks 有哪些布局
大数据·数据库·agent
ClouGence9 小时前
SQL Server CDC 能放到 Always On 备库读吗?一文讲透原理与实践
数据库·sql server
先吃饱再说1 天前
存储的进化:从 MySQL 到浏览器缓存,数据到底住在哪?
数据库
Nturmoils1 天前
字段太多看不全,ksql 的展开模式和输出控制怎么用
数据库·后端
Databend1 天前
Agent 轨迹分析与归因的数据工程实践
大数据·数据库·agent
这个DBA有点耶1 天前
SQL改写进阶:标量子查询的“隐形代价”与消除实战
数据库·mysql·架构
smallyoung1 天前
数据库乐观锁深度解析:MySQL、PostgreSQL 实战 + Spring Boot 集成指南
数据库·mysql·postgresql