systemd 计时器和关联服务的自动安装脚本
以下脚本将安装 systemd .timer 文件和关联的 .service 文件到 /etc/systemd/system/ 并启用计时器(即启动时启动)并立即启动计时器。
install_systemd_timer.sh
#!/bin/bash
# 此脚本安装并启用/启动 systemd 计时器
# 它还安装由给定计时器运行的服务文件
export NAME=MyService
cat >/etc/systemd/system/${NAME}.service <<EOF
# 在此添加 SYSTEMD 服务文件内容
EOF
cat >/etc/systemd/system/${NAME}.timer <<EOF
# 在此添加 SYSTEMD 计时器文件内容
EOF
# 启用并启动服务
systemctl enable --now ${NAME}.timer为了为你的 systemd 服务修改脚本,将 MyService 替换为你所需的服务名称在
install_systemd_timer_set_name.sh
export NAME=MyService在以下位置插入你的 .service 文件内容
install_systemd_timer_service_placeholder.sh
# 在此添加 SYSTEMD 服务文件内容并在以下位置插入你的 .timer 文件内容
install_systemd_timer_timer_placeholder.sh
# 在此添加 SYSTEMD 计时器文件内容完整示例
以下完整示例安装名为 MyService 的 systemd 服务,该服务每两小时运行 /usr/bin/python3 run.py:
install_systemd_timer_example.sh
#!/bin/bash
# 此脚本安装并启用/启动 systemd 计时器
# 它还安装由给定计时器运行的服务文件
export NAME=MyService
cat >/etc/systemd/system/${NAME}.service <<EOF
[Unit]
Description=${NAME}
[Service]
Type=oneshot
ExecStart=/usr/bin/python3 run.py
WorkingDirectory=/opt/myproject
EOF
cat >/etc/systemd/system/${NAME}.timer <<EOF
[Unit]
Description=${NAME} timer
[Timer]
OnCalendar=*-*-* 00,02,04,06,08,10,12,14,16,18,20,22:00:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
# 启用并启动服务
systemctl enable --now ${NAME}.timerCheck out similar posts by category:
Systemd
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow