在 Ubuntu 系统中,查看当前系统中已开启的定时任务主要有以下几种方式,分别针对不同类型的定时任务管理方式(如 crontab
、systemd timer
等):
查看服务器定时任务
一、查看用户级别的 Crontab 任务
每个用户都可以配置自己的定时任务:
bash
crontab -l
查看其他用户的定时任务:
bash
sudo crontab -u 用户名 -l
二、查看系统级别的 Crontab 任务
系统级任务配置通常放在以下几个文件中:
bash
cat /etc/crontab
或者:
bash
ls /etc/cron.d/
cat /etc/cron.d/*
三、查看周期性目录任务(cron.*
)
系统还有一些目录用于按时间分类执行脚本:
bash
ls /etc/cron.hourly/
ls /etc/cron.daily/
ls /etc/cron.weekly/
ls /etc/cron.monthly/
这些目录下的脚本由 /etc/crontab
控制周期执行。
四、查看 systemd 定时任务(systemd timer
)
Systemd timers 是较现代的替代 cron 的方案。
列出所有的 timer:
bash
systemctl list-timers --all
查看某个具体 timer 的详情:
bash
systemctl status your-timer-name.timer
或:
bash
journalctl -u your-timer-name.timer
五、定时任务中时间说明
┌───────────── 分钟 (0 - 59)
│ ┌─────────── 小时 (0 - 23)
│ │ ┌───────── 日期 (1 - 31)
│ │ │ ┌─────── 月份 (1 - 12)
│ │ │ │ ┌───── 星期几 (0 - 7)(0 和 7 都表示星期天)
│ │ │ │ │
│ │ │ │ │
* * * * * → 表示"每天的 05:40 执行一次"
实现定时任务
命令步骤:
- 打开当前用户的 crontab 编辑器:
bash
crontab -e
- 在文件底部添加以下内容:
bash
0 15 * * 1-5 curl -s https://xxxxxx #周一到周五每天下午3点请求接口
含义说明:
字段 | 含义 |
---|---|
0 |
分钟,整点(第0分钟) |
15 |
小时,下午3点 |
* |
每月的每天 |
* |
每年的每个月 |
1-5 |
周一到周五(1=Monday) |
curl -s |
静默请求接口 |
如果你希望记录日志,方便排错,可以写成:
bash
0 15 * * 1-5 curl -s https://***** >> /var/log/cron_update.log 2>&1
确保 cron
服务正在运行(只需一次):
bash
sudo systemctl status cron
如果看到 active (running)
,说明没问题。如果不是,执行:
bash
sudo systemctl start cron
sudo systemctl enable cron # 开机自动启动
查看当前用户的定时任务是否配置成功:
bash
crontab -l
如果是用 root 或其他用户配置的,可以分别查看:
bash
sudo crontab -l -u root
sudo crontab -l -u www-data
查看日志是否正常执行(第二天三点后):
你设置的日志文件路径为:
bash
/var/log/cron_update.log
执行后可以查看它内容:
bash
cat /var/log/cron_update.log
如你设置了日志,但文件没生成,可能是:
-
目录没写权限;
-
curl
命令有错误; -
网络不通;
-
任务没执行。
注意事项:
-
curl
命令必须在系统环境变量路径中(通常默认有)。 -
如果接口有鉴权或要传递参数,请根据实际情况修改
curl
命令。 -
确保
cron
服务已启动:bashsudo systemctl enable cron sudo systemctl start cron