Linux systemd 定时器 timer

时间:2022-04-29
本文章向大家介绍Linux systemd 定时器 timer,主要内容包括编写脚本、name.timer、name.service、启用定时器、查看定时器、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

用来取代 crontab

systemd 系列文章请查看:https://www.khs1994.com/tags/systemd/

要使用定时器必须编写两个文件:

  • name.timer 配置时间。
  • name.service 配置具体执行的命令。

注意:这两个文件的名称是相同的,只是后缀不同。

编写脚本

/usr/local/bin/name.sh

#!/bin/bash
date >> /tmp/name.txt
echo 1 >> /tmp/name.txt

/etc/systemd/system 文件夹内编写下面的两个文件。

name.timer

[Unit]
# 描述信息
Description=My systemd timer Demo

[Timer]
# 首次运行要在启动后10分钟后
OnBootSec=10min
# 每次运行间隔时间
OnUnitActiveSec=1h

[Install]
WantedBy=multi-user.target

详细信息请查看以下网址:

用法举例

[Timer]

OnCalendar=*-*-* *:*:00 # 每分钟执行,与 crontab 类似。
#       hourly → *-*-* *:00:00
#        daily → *-*-* 00:00:00
#      monthly → *-*-01 00:00:00
#       weekly → Mon *-*-* 00:00:00
#       yearly → *-01-01 00:00:00
#    quarterly → *-01,04,07,10-01 00:00:00
# semiannually → *-01,07-01 00:00:00

name.service

[Unit]
# 描述信息
Description=My systemd timer Demo

[Service]
Type=simple
ExecStart=/usr/local/bin/name.sh

启用定时器

$ sudo systemctl daemon-reload

$ sudo systemctl enable name.timer

$ sudo systemctl start name.timer

查看定时器

$ systemctl list-timer

查看日志。

$ sudo journalctl -u name.service