Skip to content

Commit

Permalink
fix(background/Heartbeat): use alarm instead of storage.set (#495)
Browse files Browse the repository at this point in the history
Co-authored-by: Radu-Cristian Popa <[email protected]>
  • Loading branch information
sidvishnoi and raducristianpopa authored Aug 8, 2024
1 parent fd9e4bd commit 8d47b3e
Showing 1 changed file with 33 additions and 9 deletions.
42 changes: 33 additions & 9 deletions src/background/services/heartbeat.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,43 @@
import type { StorageService } from '.'
import type { Browser } from 'webextension-polyfill'

export class Heartbeat {
private interval: ReturnType<typeof setInterval>

constructor(private storage: StorageService) {}
constructor(private browser: Browser) {}

start() {
this.interval = setInterval(this.run.bind(this), 20 * 1000)
}
const alarms = this.browser.alarms
// The minimum supported cross-browser period is 1 minute. So, we create 4
// alarms at a 0,15,30,45 seconds delay. So, we'll get an alarm every 15s -
// and that'll help us keep the background script alive.

// Note that the first alarm will trigger after a minute, but this maybe
// fine for our use case, as we may have enough events between start and
// first minute that our extension stays alive.
setTimeout(
() => alarms.create('keep-alive-alarm-0', { periodInMinutes: 1 }),
0
)
setTimeout(
() => alarms.create('keep-alive-alarm-1', { periodInMinutes: 1 }),
15 * 1000
)
setTimeout(
() => alarms.create('keep-alive-alarm-2', { periodInMinutes: 1 }),
30 * 1000
)
setTimeout(
() => alarms.create('keep-alive-alarm-3', { periodInMinutes: 1 }),
45 * 1000
)

run() {
void this.storage.get(['version'])
alarms.onAlarm.addListener(() => {
// doing nothing is enough to keep it alive
})
}

stop() {
clearInterval(this.interval)
this.browser.alarms.clear('keep-alive-alarm-0')
this.browser.alarms.clear('keep-alive-alarm-1')
this.browser.alarms.clear('keep-alive-alarm-2')
this.browser.alarms.clear('keep-alive-alarm-3')
}
}

0 comments on commit 8d47b3e

Please sign in to comment.