1. 确保 cron 服务已安装并运行
检查是否安装:
which crontab
如果系统中未安装,可以根据你的 Linux 发行版进行安装。例如:
对于基于 Debian 的系统(如 Ubuntu):
sudo apt update
sudo apt install cron
对于基于 Red Hat 的系统(如 CentOS):
sudo yum install cronie
启动 cron 服务:
sudo systemctl start cron
设置开机自启:
sudo systemctl enable cron
2. 编辑用户定时任务
使用 crontab -e 命令编辑当前用户的定时任务:
crontab -e
这会打开一个配置文件,你可以在这里添加定时任务。
3. 编写定时任务
定时任务的格式如下:
* * * * * command_to_be_executed
– – – – –
| | | | |
| | | | +—– 星期几 (0 – 7) (星期天为0或7)
| | | +——- 月份 (1 – 12)
| | +——— 日期 (1 – 31)
| +———– 小时 (0 – 23)
+————- 分钟 (0 – 59)
示例:
每天凌晨 2 点运行一次脚本:
0 2 * * * /path/to/your/script.sh
每小时的第 15 分钟运行一次命令:
15 * * * * /path/to/your/command
每周一的上午 9 点运行一次任务:
0 9 * * 1 /path/to/your/task.sh
4. 保存并退出
在编辑器中保存文件并退出。cron 会自动加载你添加的任务。
5. 查看定时任务
查看当前用户的定时任务:
crontab -l
6. 注意事项
脚本权限:确保脚本有可执行权限:
chmod +x /path/to/your/script.sh
环境变量:定时任务运行时可能无法继承你的用户环境变量,可以在脚本中显式定义需要的环境变量。
日志记录:如果需要记录任务的输出,可以将输出重定向到日志文件:
0 2 * * * /path/to/your/script.sh >> /path/to/logfile.log 2>&1