linux查看定时任务与设置定时任务
一、查看定时任务
- 使用 cron
查看当前用户的定时任务:
bash
crontab -l # 查看当前用户的cron任务
查看系统级定时任务:
bash
系统级任务通常存放在以下位置:
cat /etc/crontab # 系统主配置文件
ls /etc/cron.d/ # 系统级任务片段
ls /etc/cron.hourly/ # 每小时执行的任务
ls /etc/cron.daily/ # 每天执行的任务
ls /etc/cron.weekly/ # 每周执行的任务
ls /etc/cron.monthly/ # 每月执行的任务
2. 使用 systemd timer
查看已激活的定时器:
bash
systemctl list-timers --all # 列出所有定时器
3. 查看日志
定时任务执行日志通常位于:
bash
grep cron /var/log/syslog # Debian/Ubuntu
grep cron /var/log/cron # CentOS/RHEL
journalctl -u cron.service # 使用journalctl查看日志
二、设置定时任务
- 使用 cron
编辑当前用户的定时任务:
bash
crontab -e # 进入编辑模式,添加任务后保存退出
cron语法格式:
示例:
bash
0 3 * * * /path/to/backup.sh # 每天3点执行备份脚本
*/5 * * * * /path/to/check.sh # 每5分钟执行一次
@daily /path/to/cleanup.sh # 每天午夜执行(等价于 0 0 * * *)
系统级任务:
直接编辑 /etc/crontab 或在 /etc/cron.d/ 下添加配置文件(需要root权限)。
- 使用 systemd timer
步骤:
创建服务单元文件(如 myjob.service):
ini
[Unit]
Description=My Custom Job
[Service]
ExecStart=/path/to/script.sh
保存到 /etc/systemd/system/myjob.service。
创建定时器单元文件(如 myjob.timer):
ini
[Unit]
Description=Run myjob daily
[Timer]
OnCalendar=--* 03:00:00 # 每天3点执行
Persistent=true # 错过任务后立即补执行
[Install]
WantedBy=timers.target
保存到 /etc/systemd/system/myjob.timer。
启用并启动定时器:
bash
systemctl daemon-reload
systemctl enable myjob.timer
systemctl start myjob.timer
三、注意事项
环境变量:cron 默认使用精简环境变量,建议在脚本中使用绝对路径或在crontab中设置 PATH。
权限:系统级任务需root权限,用户级任务通过 crontab -e 设置。
调试:使用 tail -f /var/log/cron 或 journalctl -f 实时监控任务执行情况。