Skip to content

Execute Scripts on Period with Systemd

本教程旨在通过Systemd自带的Timer实现定时执行任务

本文以实现定时的git pull为例,讲解Systemd的定时器

1. Create a git pull Script

该脚本的主要目的为进入指定的git路径,并执行git pull指令

需要确保该路径存在一个已经clone到本地的git仓库

(1). vim gitpull.sh内容如下:

#!/bin/sh
cd ${pwd_of_git_repo_path}
git pull

${pwd_of_git_repo_path}表示git仓库的文件夹

(2). 编辑完后保存退出:wq,为脚本添加运行权限:

sudo chmod +x gitpull.sh

(3). 测试脚本是否可运行

命令行运行./gitpull.sh,当命令行出现和正常运行git pull指令一样的输出时,说明脚本正常

2. Create gitpull.service

(1). 在/etc/systemd/system/或者/usr/lib/systemd/system/目录中创建一个名为gitpull.service的文件,内容如下:

[Unit]
Description=gitpull service

[Service]
User=${USER}
Group=${GROUP}
ExecStart=/bin/bash ${pwd_of_scripts}/gitpull.sh

[Install]
WantedBy=multi-user.target

${pwd_of_scripts} 表示上一步创建的脚本所在文件夹 \({USER}表示执行脚本的用户,\)表示用户所在组

(2). 测试Service

重载并运行gitpull.service

sudo systemctl daemon-reload
sudo systemctl start gitpull.service
查看Systemd的输出日志,确定service是否正常运行,输出与直接git pull是否相同
sudo systemctl status gitpull.service

3. Create gitpull.timer

(1). 创建定时器,内容如下:

[Unit]
Description=run gitpull.sh every 1hour

[Timer]
OnUnitActiveSec=1h
Unit=gitpull.service

[Install]
WantedBy=multi-user.target

Timer的名称需要与Service的名称一致

OnUnitActiveSec表示运行定时器运行的间隔

Oncalnedar表示在特定时间运行

Unit表示需要运行的service

  • Oncalnedar * *-*-* *:*:*
  • * - To signify the day of the week eg:- Sat,Thu,Mon
  • *-*-*- To signify the calendar date. Which means it breaks down to - year-month-date.
    • 2021-10-15 is 15th of October
    • *-10-15 means every year at 15th October
    • *-01-01 means every new year.
  • *:*:* is to signify the time component of the calnedar event. So it is - hour:minute:second

(2). 运行测试Timer

sudo systemctl daemon-reload
sudo systemctl start gitpull.timer
检查gitpull.servicegitpull.timer的运行状态和输出
sudo systemctl status gitpull.service
sudo systemctl status gitpull.timer

4. Run Timer on Boot

sudo systemctl enable gitpull.service
sudo systemctl enable gitpull.timer

REF

[1]. http://www.ruanyifeng.com/blog/2018/03/systemd-timer.html

[2]. https://silentlad.com/systemd-timers-oncalendar-(cron)-format-explained