1、初始化crontab
执行命令 crontab -e
no crontab for username - using an empty one
Select an editor. To change later, run 'select-editor'.1. /bin/nano <---- easiest2. /usr/bin/vim.basic3. /usr/bin/vim.tiny4. /bin/ed
选择第一项 /bin/nano即可,确认后输入定时任务的执行命令
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
# 添加一个执行脚本,每天凌晨1点运行一个nginx的重启
0 1 * * * /root/script/reloadNginx.sh
2、创建脚本文件reloadNginx.sh
# 进入目录
cd /root/script/
#编辑文件
vim reloadNginx.sh
#录入内容
main(){docker exec -i "nginx-proxy" /bin/bash -c "nginx -s reload && exit"
}
main
# 保存文件并退出
:wq
#赋予文件权限,不设置,定时任务执行时会报错权限不足
chmod 777 ./reloadNginx.sh
3、修改crontab为输出日志文件
crontab执行默认会发送邮件,如果不进行相关配置,可能会导致定时任务不执行。我们不需要邮件,修改命令,令其输出日志文件即可
#编辑crontab
crontab -e#修改定时任务结束后的输出
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
# 添加一个执行脚本,每天凌晨1点运行一个nginx的重启
0 1 * * * /root/script/reloadNginx.sh >> /root/script/reloadNginx.log 2>&1
这样定时任务就执行完毕了,如果产生了异常,通过日志reloadNginx.log排查即可。