如何在Linux中设置定时任务?

在Linux中,可以通过以下方式设置定时任务:

  1. 使用 crontab 定时任务:
    crontab用于设置定期执行的命令。配置文件在/etc/crontab。常用命令有:
# 编辑crontab文件
crontab -e  

# 删除crontab文件  
crontab -r

# 检查crontab文件  
crontab -l

crontab文件格式:

* * * * * command
- - - - -
| | | | |
| | | | |
| | | | +-- 星期(0-6)(0 is Sunday)
| | | +---- 月(1-12) 
| | +------ 日(1-31)
| +-------- 小时(0-23)
+---------- 分钟(0-59)

示例:

# 每小时执行一次
* * * * * /path/to/script

# 晚上11点到早上7点之间每小时执行一次  
0 23-7 * * * /path/to/script  

# 每天晚上11点30分执行  
30 23 * * * /path/to/script
  1. 使用 systemd 定时器:
    systemd是Linux通用的初始化系统,其中包含了定时器功能。配置文件在/etc/systemd/system/目录下。常用命令有:
# 重新载入配置  
sudo systemctl daemon-reload   

# 启动定时器   
sudo systemctl start timer-name.timer  

# 查看定时器状态        
systemctl status timer-name.timer  

# 停止定时器         
sudo systemctl stop timer-name.timer   

定时器文件timer-name.timer示例:

[Unit]
Description=Run script every 2 minutes

[Timer]
OnCalendar=*:0/2

[Install]
WantedBy=timers.target