Execute Scripts on Period with Systemd
Execute Scripts on Period with Systemd
Section titled “Execute Scripts on Period with Systemd”本教程旨在通过Systemd自带的Timer实现定时执行任务
本文以实现定时的git pull为例,讲解Systemd的定时器
1. Create a git pull Script
Section titled “1. Create a git pull Script”该脚本的主要目的为进入指定的git路径,并执行git pull指令
需要确保该路径存在一个已经clone到本地的git仓库
(1). vim gitpull.sh内容如下:
Section titled “(1). vim gitpull.sh内容如下:”#!/bin/shcd ${pwd_of_git_repo_path}git pull${pwd_of_git_repo_path}表示git仓库的文件夹
(2). 编辑完后保存退出:wq,为脚本添加运行权限:
Section titled “(2). 编辑完后保存退出:wq,为脚本添加运行权限:”sudo chmod +x gitpull.sh(3). 测试脚本是否可运行
Section titled “(3). 测试脚本是否可运行”命令行运行./gitpull.sh,当命令行出现和正常运行git pull指令一样的输出时,说明脚本正常
2. Create gitpull.service
Section titled “2. Create gitpull.service”(1). 在/etc/systemd/system/或者/usr/lib/systemd/system/目录中创建一个名为gitpull.service的文件,内容如下:
Section titled “(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}表示执行脚本的用户,${GROUP}表示用户所在组
(2). 测试Service
Section titled “(2). 测试Service”重载并运行gitpull.service
sudo systemctl daemon-reloadsudo systemctl start gitpull.service查看Systemd的输出日志,确定service是否正常运行,输出与直接git pull是否相同
sudo systemctl status gitpull.service3. Create gitpull.timer
Section titled “3. Create gitpull.timer”(1). 创建定时器,内容如下:
Section titled “(1). 创建定时器,内容如下:”[Unit]Description=run gitpull.sh every 1hour
[Timer]OnUnitActiveSec=1hUnit=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
Section titled “(2). 运行测试Timer”sudo systemctl daemon-reloadsudo systemctl start gitpull.timer检查gitpull.service和gitpull.timer的运行状态和输出
sudo systemctl status gitpull.servicesudo systemctl status gitpull.timer4. Run Timer on Boot
Section titled “4. Run Timer on Boot”sudo systemctl enable gitpull.servicesudo systemctl enable gitpull.timer[1]. http://www.ruanyifeng.com/blog/2018/03/systemd-timer.html
[2]. https://silentlad.com/systemd-timers-oncalendar-(cron)-format-explained
[3]. Systemd-初探