-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Radu-Cristian Popa <[email protected]>
- Loading branch information
1 parent
fd9e4bd
commit 8d47b3e
Showing
1 changed file
with
33 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | ||
} | ||
} |