Systemd user timer
Systemd user timerを使ってBing壁紙を定期的にダウンロードしてみます。
環境
- CachyOS
構築
定期的に実行する処理の作成
- Bing壁紙をダウンロード
今日の壁紙画像を~/Pictures/Wallpapers/bing/にダウンロードします。
Systemd user timerは登録したユーザアカウントで実行され、環境変数が引き継がれるらしい。/home/arch/bin/download_bing_wallpaper.py #!/usr/bin/env python
import requests
import json
import subprocess
import shutil
import os
REGION = 'en-US'
BASE_URL = f'https://bing.biturl.top/?resolution=UHD&format=json&index=0&mkt={REGION}'
BASE_PATH = os.getenv('HOME') + '/Pictures/Wallpapers/bing/'
CURRENT_BACKGROUND = BASE_PATH + 'current.jpg'
u = requests.get(BASE_URL).json()
r = requests.get(u['url'], stream=True)
name = u['url'].split('=')[-1]
filename = os.path.join(BASE_PATH, name)
with open(filename, 'wb') as file:
for chunk in r.iter_content(chunk_size=8192):
file.write(chunk)chmod 755 /home/arch/bin/download_bing_wallpaper.py
ユニットファイル
- サービスユニット
/home/arch/bin/download_bing_wallpaper.pyを実行します。~/.config/systemd/user/download-bing-wallpaper.service [Unit]
Description=Download Bing wallpaper
[Service]
Type=oneshot
ExecStart=/home/arch/bin/download_bing_wallpaper.py
[Install]
WantedBy=default.target - タイマーユニット
毎日5時に実行します。~/.config/systemd/user/download-bing-wallpaper.timer [Unit]
Description=Run daily
[Timer]
OnCalendar=*-*-* 05:00:00
Persistent=true
[Install]
WantedBy=timers.target
ユーザタイマーの登録
- ユーザタイマーを有効化
systemctl --user daemon-reload
systemctl --user enable --now download-bing-wallpaper.timer - スケジュールされたユーザタイマーを確認
systemctl --user list-timers --all
NEXT LEFT LAST PASSED UNIT ACTIVATES
Sun 2025-12-21 05:00:00 JST 4min 25s - - download-bing-wallpaper.timer download-bing-wallpaper.service
1 timers listed.
Comments