在Linux系统中,定时执行任务主要通过cron
服务实现,也可以通过at
命令实现单次任务。以下是详细方法:
crontab -e # 编辑当前用户的定时任务
bash
0 3 * * * /path/to/backup.sh # 每天凌晨3点执行
*/5 * * * * /path/to/check_status.sh # 每5分钟执行一次
编辑/etc/crontab
或/etc/cron.d/
目录下的文件(需root权限):
sudo vim /etc/crontab
bash
0 1 * * * root /path/to/system_clean.sh
grep CRON /var/log/syslog # Ubuntu/Debian
grep CRON /var/log/cron # CentOS/RHEL
sudo apt install at # Debian/Ubuntu
sudo yum install at # CentOS/RHEL
echo "command_to_execute" | at 3:00 PM 2024-06-15
# 或交互式输入:
at now + 1 hour
> /path/to/script.sh
> Ctrl+D 保存
atq
atrm <任务ID>
anacron
适用于不24小时开机的系统,处理错过执行的周期性任务(配置文件在/etc/anacrontab
)。
systemd timer
现代Linux发行版替代cron的方案,需搭配.service
和.timer
单元文件使用。
PATH
。chmod +x script.sh
)。根据需求选择合适的方式,多数场景推荐使用cron
。如果是临时任务,at
更方便。