温馨提示×

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

小樊
56
2025-09-08 13:32:09
栏目: 智能运维

在Ubuntu中,可使用cronsystemd设置任务执行时间,具体如下:

  • 使用Cron
    1. 打开终端,输入crontab -e编辑当前用户的crontab文件。
    2. 按格式分 时 日 月 星期 命令添加定时任务,例如0 6 * * * /path/to/script.sh表示每天早上6点执行脚本。
    3. 保存并退出编辑器,cron会自动加载新配置。
  • 使用Systemd
    1. 创建服务文件,如/etc/systemd/system/mytask.service,内容为[Unit] Description=My Task [Service] ExecStart=/path/to/script.sh
    2. 创建定时器文件,如/etc/systemd/system/mytask.timer,内容为[Unit] Description=Run My Task [Timer] OnCalendar=*-*-* 06:00:00 Persistent=true [Install] WantedBy=timers.target,其中OnCalendar指定执行时间。
    3. 启用并启动定时器:sudo systemctl enable --now mytask.timer

0