Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(background/Heartbeat): use alarm instead of storage.set #495

Merged
merged 2 commits into from
Aug 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
})
}
sidvishnoi marked this conversation as resolved.
Show resolved Hide resolved

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')
}
}
Loading