配置 systemd 以在启动时管理服务

配置 systemd 以在启动时管理服务

我有一个脚本,可以从网页下载图片并将其设置为我的桌面壁纸。该代码运行正常,但我无法让它在启动时运行。

我正在尝试通过配置 systemd 来管理服务来做到这一点。(重新启动时 crontab 对我来说不起作用,但这是另一个问题)。

我创建了一个文件/etc/systemd/system/apod.service

[Unit]
Description=Set APOD as Desktop

[Install]
WantedBy=multi-user.target

[Unit]
Wants=network-online.target
After=network-online.target

[Service]
ExecStart=/bin/bash /home/me/apod.sh
Type=simple
User=me
Group=me
WorkingDirectory=/home/me
Restart=on-failure

但当我启动时它似乎不起作用。如果我检查systemctl status apod,我会看到:

Jun 04 20:55:55 me-XPS-15-9500 systemd[1]: Started Set APOD as Desktop.
Jun 04 20:55:57 me-XPS-15-9500 gsettings[1598]: failed to commit changes to dconf: Could not connect: No such file or directory

但如果我只是手动运行/bin/bash /home/me/apod.sh,它就能完美运行。

欢迎提出任何建议。我正在运行 18.04。


为了完整性:

Bash 脚本:

#!/bin/sh                                                                                                 

export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$(id -u)/bus"

python /home/me/apod.py

/usr/bin/gsettings set org.gnome.desktop.background picture-uri "file:///home/me/Downloads/apod.jpg"

它调用的python脚本:

from bs4 import BeautifulSoup as BSHTML
import requests
import subprocess
import urllib2
page = urllib2.urlopen('https://apod.nasa.gov/apod/astropix.html')
soup = BSHTML(page,features="html.parser")
images = soup.findAll('img')

url = 'https://apod.nasa.gov/apod/'+images[0]['src']
r = requests.get(url, allow_redirects=True)
with open('/home/me/Downloads/apod.jpg',"w") as f:
            f.write(r.content)

答案1

您无法在系统启动脚本中更改背景,因为您的图形环境尚未启动。我建议将您的脚本添加到 gnome-tweaks 中的启动应用程序中。

这实际上分为两个部分。

一个是您所做的 gsettings 更改 - 这实际上是永久性的,不需要重复,除非其他东西正在更改它并且您想要重置它,或者您想要更改文件名。

另一个是下载图像,如果您替换文件而不是使用新名称,它可能会立即改变。

尽管存在 network-online.target 依赖项,但下载也可能在启动时失败,因为运行时网络可能尚未完全启动。修复此问题会延迟系统启动 - 最好在登录启动期间完成此操作。

答案2

我使用过类似的系统,所以你应该能够让它与 systemd 一起工作。你可以在服务文件中包含一个 systemd 计时器,以便在你登录后在启动时触发服务运行。由于设置壁纸不需要 root 权限,你可以按照 @Jeff Schaller 的建议创建一个 systemd 用户服务。你可以将 systemd 用户文件存储在$HOME/.config/systemd/user

您可以将 apod.service 文件修改为类似以下内容:

[Unit]
Description=Set APOD as Desktop
After=network.target
After=systemd-user-sessions.service
After=network-online.target

[Install]
WantedBy=multi-user.target

[Service]
Type=simple
ExecStart=/bin/bash /home/me/apod.sh

添加一个名为 apod.timer 的文件

[Unit]
Description=Timer for apod.service

[Timer]
OnBootSec=0 min

[Install]
WantedBy=timers.target

像平常一样放置apod.serviceapod.timer启用$HOME/.config/systemd/user/ 它们,但不要使用 root 权限/调用 sudo,而是以普通用户的身份执行此操作并将标志添加--user到命令中:

systemctl --user enable apod.timer

systemctl --user enable apod.service

编辑:从链接的 NASA 源获得的今天日期的“图像”似乎是一个视频,因此这可能是需要注意的事情。

编辑2:停止启用.service除了.timer

答案3

正如您所说,它是通过手动执行来工作的,我认为您应该通过 crontab 选择不同的方式。

执行:
sudo crontab -e
然后在最后添加一行,如下所示
@reboot /bin/bash /home/me/apod.sh

重新启动并查看是否有效。

您还可以更改@reboot,它将在启动后每小时左右运行一次(请参阅 cron 手册)。

类似这样的事情(在 crontab 中)将每小时发生一次。

0 * * * * /bin/bash /home/me/apod.sh

希望这有帮助,祝你好运。

相关内容