Crontab 定时任务配置

2017/09/09 crontab

# 基本格式

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

栗子:

# 每晚的 21:30 重启服务
30 21 * * * /usr/local/etc/rc.d/lighttpd restart

# 每月 1、10、22 日的 4:45 重启服务
45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart

# 每周六、周日的 1:10 重启服务
10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart

# 每天 18:00 至 23:00 之间每隔 30 分钟重启服务
0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart

# 每一小时重启服务
0 */1 * * * /usr/local/etc/rc.d/lighttpd restart

# 晚上 11 点到早上 7 点之间,每隔一小时重启服务
0 23-7/1 * * * /usr/local/etc/rc.d/lighttpd restart

# 常用命令

# 启动服务
service crond start

# 关闭服务
service crond stop

# 重启服务
service crond restart

# 重新载入配置
service crond reload

# 设定某个用户的 cron 服务,一般 root 用户在执行这个命令的时候需要此参数
crontab -u

# 列内容
crontab -l

# 删除 cron 服务
crontab -r

# 编辑 cron 服务
crontab -e

# 常见问题

# xxx command not found 报错

这是因为 crontab 不会从用户 profile 文件中读取环境变量参数,解决在网上能找到很多方案,但是试过之后很多都没有成功,最后发现只要在命令前面加上 PATH=$PATH 就可以了,如下:

# 打开 crontab 编辑文件
crontab -e

# 编辑文件
PATH=/usr/local/bin:/usr/local/sbin:/home/iot/.local/share/pnpm:/
# 每天凌晨 3 点重启服务
* 3 * * * /usr/local/etc/rc.d/lighttpd restart

# 参考资料

上次更新: 2025/1/24 08:03:38