Skip to content

Instantly share code, notes, and snippets.

@zhangguanzhang
Created December 20, 2024 09:34
Show Gist options
  • Save zhangguanzhang/abd6d1f2aadd2adb8bbe649893f2c3dc to your computer and use it in GitHub Desktop.
Save zhangguanzhang/abd6d1f2aadd2adb8bbe649893f2c3dc to your computer and use it in GitHub Desktop.
linux systemd timer demo

关于

大致写下快速写一个 systemd 的定时任务,不使用 cron 是因为 cron 比较弱,而且日志查看不友好。

文件

需要有一个 service 文件和 timer 文件,前者描述启动相关,后者描述定时相关属性

cat > /etc/systemd/system/gitlab-runner.service << EOF
[Unit]
Description=crontab for docker-compose up gitlab-runner

[Service]
Type=simple
WorkingDirectory=/data/xxx
ExecStart=/bin/bash /data/xxx/basefiles/ci_tools/scripts/gitlab-runner.sh
StandardOutput=syslog
StandardError=syslog
EOF

timer 文件

cat > /etc/systemd/system/gitlab-runner.timer << EOF
[Unit]
Description=crontab for docker-compose up gitlab-runner

[Timer]
OnCalendar=*-*-* 03:40:00
Persistent=true

[Install]
WantedBy=timers.target
EOF

开启:

systemctl enable gitlab-runner.timer

OnCalendar 说明

OnCalendar 实际可以设置多个,OnCalendar 格式为如下,周可以忽略

  • 周 年-月-日 时:分:秒
  • 年-月-日 时:分:秒

逗号,列举枚举数值,range 用 .. 连接,下面是一些例子:

# 每个月第一天或者第三天
*-*-1,3 03:40:00

# 每个月第4天到第7天
*-*-4..7 03:40:00

# 周日凌晨1点
Sun *-*-* 01:00:00

对于 OnCalendar 可以有命令计算下一次执行时间,附带距离现在还有多久:

systemd-analyze calendar '*-*-* 03:40:00'

比较老的 systemd 包的 systemd-analyze 没有 calendar 子命令。

查看相关

# 查看定时任务
systemctl list-timers --all

systemctl cat --no-pager gitlab-runner.*

systemd-analyze verify /etc/systemd/system/gitlab-runner.*

这样的定时服务日志就能使用 journalctl 查看了:

journalctl -xe --no-pager -u gitlab-runner

参考文档

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment