0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ラズパイでお昼のチャイムを鳴らす

Last updated at Posted at 2025-10-16

お昼のチャイムがあると気持ちの切り替えが早そうなので転がってたラズパイでサクッと実装しました。

  • 開始の12:00と終了の13:00にチャイムを鳴らす
  • 時刻同期はデフォルトのsystemd-timesyncdを信用する
  • 土日祝日には鳴らないようにする

「祝日には鳴らない」を実現するためにPythonのjpholidayを使いました。cronやシェルスクリプトだとここが難しかったです。使用した外部ライブラリは次の通り。

  • jpholiday
    日本の祝日を収録しており判定できる
  • schedule
    定刻実行を関数デコレータで明瞭に書ける
  • pydub
    音源の再生に使用

コードは次の通り。scheduleで12:00と13:00に関数を実行し、土日でない/祝日でないことを確認した後にコードと同ディレクトリに置いたchime.mp3を再生します。DEBUG定数は一種のおまじないで後述のデーモン化した時にログの優先度として認識されて冗長なログが不要な時に非表示できる様になります。

#!/usr/bin/python3

from os.path import abspath, dirname
from datetime import datetime
from time import sleep

from jpholiday import is_holiday
from schedule import repeat, every, run_pending
from pydub import AudioSegment
from pydub.playback import play

DEBUG = "<7>"
sound = AudioSegment.from_mp3(abspath(dirname(__file__)) + "/chime.mp3")

@repeat(every().day.at("12:00"), "12:00")
@repeat(every().day.at("13:00"), "13:00")
def job(now):
  today = datetime.today()
  if today.weekday() < 5:
      if not is_holiday(today):
          print("Play chime.  Now is " + now + ".", flush=True)
          play(sound)
      else:
          print(DEBUG + "Chime was muted because of public holiday.", flush=True)
  else:
      print(DEBUG + "Chime was muted because of holiday.", flush=True)

if __name__ == "__main__"
    print(DEBUG + "Start chime daemon.", flush=True)
    while True:
        run_pending()
        sleep(1)

ラズパイでは必要なライブラリのインストールと、systemdに登録してデーモン化を行いました。

$ sudo apt update && sudo apt install python3-pip ffmpeg
$ sudo -H pip3 install jpholiday schedule pydub
$ sudo cat << EOF | sudo tee /etc/systemd/chime.service
[Unit]
Description = Chime daemon
[Service]
ExecStart = ${PWD}/chime.py
User = ${USER}
Restart = always
Type = simple
[Install]
WantedBy = multi-user.target
EOF
$ sudo systemctl enable chime
$ sudo systemctl start chime
$ sudo systemctl status chime

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?