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

在Linux中设置定时任务主要有两种方式:

  1. crontab:
    crontab是Linux内置的定时任务调度器,可以根据我们设置的定时规则运行任务。
    crontab相关命令有:
  • crontab -e: 编辑crontab文件,设置定时任务。
  • crontab -l: 列出当前定时任务。
  • crontab -r: 删除当前定时任务。
    crontab文件格式如下:
*     *     *     *     *     command
分   时     日    月    周     命令

例如,每天晚上11点运行backup.sh脚本:

0 23 * * * /home/backup/backup.sh
  1. systemd timer:
    systemd是Linux系统中较新的初始化系统,提供了强大的timer服务管理定时任务。
    timer相关命令有:
  • systemctl list-timers:列出当前系统下所有的定时器。
  • systemctl start timer-name:启动某个定时器。
  • systemctl stop timer-name:停止某个定时器。
  • systemctl enable timer-name:设置某个定时器开机启动。
    定时器文件保存在/usr/lib/systemd/system目录下,文件扩展名为.timer,格式如下:
[Unit]
Description=Run the backup script

[Timer]
# Run once a day at 11pm 
OnCalendar=*-*-* 23:00:00

[Install] 
WantedBy=timers.target
ini
[Unit]
Description=Run the backup script

[Service] 
ExecStart=/home/backup/backup.sh

例如,创建/usr/lib/systemd/system/backup.timer和/usr/lib/systemd/system/backup.service文件,实现每天晚上11点运行backup.sh脚本的定时任务。
crontab和systemd timer是Linux上常用的两种定时任务解决方案。crontab更为轻量简单,适用于小范围定时任务;systemd timer功能更丰富完善,管理更加集中化,适用于大规模定时任务。