Service workers replace background pages in manifest v3 chrome extensions, and I'm trying to use one for my extension. I need to be able to run a function periodically, and it looks like alarms are the way to go. In the example they recommend doing this in the top level of the service worker:
chrome.alarms.create({ delayInMinutes: 3.0 });
chrome.alarms.onAlarm.addListener(() => {
chrome.action.setIcon({
path: getRandomIconPath(),
});
});
From what I understand though, weather or not my service worker gets killed in between events is non-deterministic. I believe if the browser kills my service worker this will be called every 3 minutes, since when the script is re-started to handle the alarm, it will run the first line again and queue up another alarm.
By contrast, if the browser lets my service worker live for the 3 minutes in between alarms this won't loop, because it will only call addListener() once, but will call the callback twice (once for the first alarm that originally spawned this service worker, and again for the alarm registered on the first line of this invocation of the service worker). The service worker will then eventually die and no alarm will ever wake it again.
Am I misunderstanding how events work here? If not, how do I register a re-occurring alarm once chrome.alarms.create({ periodInMinutes: 3.0 }); and avoid re-registering it every time my service worker is re-started?
NOTE: delayInMinutes fires once, periodInMinutes is re-ocuring.