温馨提示×

ubuntu定时器如何设置任务执行间隔

小樊
54
2025-09-08 13:33:15
栏目: 智能运维

在Ubuntu中,可通过cronsystemd设置任务执行间隔,具体如下:

1. 使用cron(推荐)

  • 编辑用户定时任务:终端输入 crontab -e,添加如下格式的任务(*为通配符,/n表示每隔n单位时间):
    • 每5分钟执行一次*/5 * * * * /path/to/command
    • 每小时的第30分钟执行30 * * * * /path/to/command
    • 每天凌晨3点执行0 3 * * * /path/to/command
  • 保存并重启cron:保存后执行 sudo service cron restart(部分系统需用 sudo systemctl restart cron)。

2. 使用systemd(适合系统级任务)

  • 创建服务文件(如 /etc/systemd/system/mytask.service):
    [Unit]
    Description=My Task
    [Service]
    ExecStart=/path/to/command
    
  • 创建定时器文件(如 /etc/systemd/system/mytask.timer):
    [Unit]
    Description=Run My Task every 5 minutes
    [Timer]
    OnUnitActiveSec=5min  # 间隔5分钟执行
    Unit=mytask.service
    [Install]
    WantedBy=timers.target
    
  • 启用并启动定时器
    sudo systemctl enable --now mytask.timer
    sudo systemctl list-timers  # 查看定时器状态
    

注意事项

  • 确保命令或脚本具有可执行权限(chmod +x /path/to/command)。
  • cron语法中,*/n表示“每隔n单位”,*表示“任意值”,逗号(,)和横杠(-)可用于指定多个时间点。

0