1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Google拡張機能で毎日同じ時間に起動するアラームをセットしたい!

Posted at

はじめに

Google拡張機能を作っている際に、backgroundで毎日同じ時間に起こる使用を作ろうとしました。
調べてみるとchrome.alarmsという物があり、その中のdelayInMinutesperiodInMinutesで作ってみましたが、アラームの起動時間からdelayInMinutes後に起動する設定になってしまいました。この場合Chromeを開いていない時間にアラームが起動することはないため次にChromeを開いた時にアラームが起動します。その時刻からperiodInMinutes後の時刻に次のアラームがセットされ、毎日同じ時間に起動するアラームにはできませんでした。
そのため今回はアラームが起動した時に次のアラームをセットする実装を行いました。

実装

const STORAGE_KEY = "daily-alarm"

chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name === STORAGE_KEY) {
    //ここに毎日行いたい実装を加える
    chrome.alarms.clear(STORAGE_KEY)
    setResetAlarm()
  }
})

const setDailyAlarm = () => {
  const now = new Date()
  //今回は深夜0時に設定
  const nextMidnight = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate() + 1,
    0,
    0,
    0
  )
  const when = nextMidnight.getTime()
  chrome.alarms.create(STORAGE_KEY, { when })
}

以上のコードを既存のコードに加え、一度setDailyAlarmを呼び出すことで、特定の時間に起動するアラームを再起的にセットすることができます。

自分は以下の部分で実装を行いました。

終わりに

今回はGoogle拡張機能で毎日同じ時間に起動するアラームを再帰関数を用いて、
「アラームセット」→「アラーム起動+アラームリセット+アラームセット」を繰り返し行うように実装しました。
違うやり方があったり、もっといい方法あるよーとかあったらじゃんじゃんコメント待っています。
最後まで読んでいただきありがとうございました。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?