【Linux】crontab 定时任务 遇到几个问题

cron 与 crontab 区别

cron 是提供定时任务的服务
crontab 是在cron服务下具体每一条任务,可以理解为 cron table

bash xxx.sh 可以执行,但是crontab定时任务不执行,也没有报错信息,无日志;

* * * * * /root/xxx.sh /root/xxx.conf 1>/dev/null 2>&1

首先区分 crontab -e 和 /etc/crontab

  • 使用命令 crontab -e 然后直接编辑定时脚本。 时间 +具体的名字
  • 这样执行以后,属于用户自定义的,会被写到 /var/spool/cron 目录下,生成一个和用户名一致的文件,文件内容就是我们编辑的定时脚本。
  • (系统级的)做系统级配置我们会直接配置 /etc/crontab
  • (用户级的)一般还是建议大家使用 crontab -e ,这样系统也会帮着检查我们配置的脚本语法。
  • 如果用户级别定时任务(crontab -e)不能执行,可以尝试 改为 系统级别定时任务(/etc/crontab)

crond[1655]: (bash) ERROR (getpwnam() failed)

  • 场景:
    /etc/crontab中,写入 * * * * * bash /root/xxx.sh /root/xxx.conf 1>/dev/null 2>&1,报错crond[1655]: (bash) ERROR (getpwnam() failed)
  • 解决:
没有写用户root导致
* * * * * /root/xxx.sh /root/xxx.conf 1>/dev/null 2>&1 错误写法

# *  *  *  *  * user-name  command to be executed
* * * * * root /root/xxx.sh /root/xxx.conf 1>/dev/null 2>&1 正确的方式

定时任务输出内容写入 /var/spool/mail/root 文件

# 去掉末尾 2>&1
* * * * * root /root/xxx.sh /root/xxx.conf 1>/dev/null

日志信息:Removed slice User Slice of root.

/var/log/messages 文件部分信息

systemd: Created slice User Slice of root.
systemd: Started Session 1529 of user root.
systemd: Removed slice User Slice of root.

解决

这些是与片的创建和删除有关的消息,这些消息在systemd中用于对进程进行分组并管理其资源。
为什么默认情况下会记录它们,这使我无所适从,但是我已经看到了两种禁用它们的方法:
较少干扰的方法是通过创建具有以下内容的/etc/rsyslog.d/ignore-systemd-session-slice.conf来过滤掉它们:

if $programname == "systemd" and ($msg contains "Starting Session" or $msg contains "Started Session" or $msg contains "Created slice" or $msg contains "Starting user-" or $msg contains "Removed Slice" or $msg contains "Stopping user-") then stop

然后重新启动rsyslogd systemctl restart rsyslog

更广泛的方法是通过编辑将systemd日志记录级别设置得更高一些/etc/systemd/system.conf:

#LogLevel=info
LogLevel=notice

参考:
https://unix.stackexchange.com/questions/267965/system-log-full-of-session-and-slice-messages
https://access.redhat.com/solutions/1564823

crontab定时任务不执行注意点

  1. 脚本中涉及文件路径时写绝对路径

  2. 脚本执行要用到环境变量时,通过source命令显式引入,例如:

#!/bin/sh
source/etc/profile
  1. 当手动执行脚本没问题,但是crontab不执行时,可以尝试在crontab中直接引入环境变量解决问题,例如:
0 * * * * /etc/profile;/bin/sh/path/to/myscript.sh

参考链接:
https://zhang.ge/5093.html

docker container 使用crontab

见:https://muguang.me/it/2659.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章