本文介绍在Ubuntu20.04系统上创建一个 systemd
服务,延迟 3 秒启动 glmark2-es2
。
1. 创建 neardi-auto.sh 脚本
启动时运行 glmark2-es2
测试,新建脚本 /usr/local/bin/neardi-auto.sh
。
sudo vi /usr/local/bin/neardi-auto.sh
#!/bin/bash
# 等待3秒
sleep 3
# 设置 XAUTHORITY 以确保脚本可以访问当前用户的 X 会话
export XAUTHORITY=/home/neardi/.Xauthority
# 设置 DISPLAY 环境变量,以指向默认的显示器
export DISPLAY=:0
# 进行图形性能测试
glmark2-es2
使脚本可执行:
sudo chmod +x /usr/local/bin/neardi-auto.sh
2. 创建 systemd 服务文件
新建文件/etc/systemd/system/neardi-auto.service
。
sudo vi /etc/systemd/system/neardi-auto.service
[Unit]
Description=Neardi Auto Service
# 定义服务在图形界面启动后再启动
After=graphical.target
[Service]
Type=oneshot
RemainAfterExit=yes
# 使用neardi用户执行脚本
ExecStart=/bin/su - neardi -c "/usr/local/bin/neardi-auto.sh"
Environment=DISPLAY=:0
Environment=XAUTHORITY=/home/neardi/.Xauthority
[Install]
WantedBy=default.target
3. 启用和启动服务
# 重新加载 systemd 配置以识别新的服务文件
sudo systemctl daemon-reload;
# 启用服务,使其在系统启动时自动运行
sudo systemctl enable neardi-auto.service;
# 立即启动服务以测试配置
sudo systemctl start neardi-auto.service
# 检查服务状态以确保正常运行
sudo systemctl status neardi-auto.service
正常返回结果,带SUCCESS
字段:
neardi@LKD3568:~$ sudo systemctl status neardi-auto.service
[sudo] password for neardi:
● neardi-auto.service - Neardi Auto Service
Loaded: loaded (/etc/systemd/system/neardi-auto.service; enabled; vendor preset: enabled)
Active: active (exited) since Mon 2024-09-02 13:52:09 UTC; 11min ago
Process: 558 ExecStart=/bin/su - neardi -c /usr/local/bin/neardi-auto.sh (code=exited, status=0/SUCCESS)
Main PID: 558 (code=exited, status=0/SUCCESS)
Sep 02 13:46:20 LPA3568 systemd[1]: Starting Neardi Auto Service...
Sep 02 13:46:20 LPA3568 su[558]: (to neardi) root on none
Sep 02 13:46:20 LPA3568 su[558]: pam_unix(su-l:session): session opened for user neardi by (uid=0)
Sep 02 13:52:09 LPA3568 systemd[1]: Finished Neardi Auto Service.