编写定时任务脚本
bash
cat >> /usr/local/bin/smem.sh <<-"EOF"
if [[ ! -d /var/log/smem ]];then
mkdir -p /var/log/smem
fi
smem -tk >> /var/log/smem/smem.log
EOF
chmod 755 /usr/local/bin/smem.sh
配置定时任务
bash
echo "" >> /etc/crontab
echo "* * * * * root flock -xn '/tmp/smem.lock' -c '/usr/local/bin/smem.sh' > /dev/null 2>&1" >> /etc/crontab
systemctl reload crond
配置日志轮转
bash
cat >> /etc/logrotate.d/smem <<-"EOF"
/var/log/smem/smem.log {
daily
rotate 30
compress
delaycompress
missingok
notifempty
create 644 root root
}
EOF
检查定时任务是否生效
bash
# 查看 /var/log/cron
tail -1000 /var/log/cron |grep smem
# 这将显示过去 2 分钟内的 crond 日志条目
journalctl -u crond --since "2 minutes ago" | grep smem
bash
[root@localhost lxm]# tail -1000 /var/log/cron |grep smem
Dec 20 10:13:01 localhost CROND[3378740]: (root) CMD (flock -xn '/tmp/smem.lock' -c '/usr/local/bin/smem.sh' > /dev/null 2>&1)
Dec 20 10:13:01 localhost CROND[3378739]: (root) CMDEND (flock -xn '/tmp/smem.lock' -c '/usr/local/bin/smem.sh' > /dev/null 2>&1)
[root@localhost lxm]#
[root@localhost lxm]# journalctl -u crond --since "2 minutes ago" | grep smem
Dec 20 10:13:01 localhost.localdomain CROND[3378740]: (root) CMD (flock -xn '/tmp/smem.lock' -c '/usr/local/bin/smem.sh' > /dev/null 2>&1)
Dec 20 10:14:01 localhost.localdomain CROND[3388194]: (root) CMD (flock -xn '/tmp/smem.lock' -c '/usr/local/bin/smem.sh' > /dev/null 2>&1)