I have an extension that is using the Alarms API to trigger at the top of each hour. However, the Alarms API does not seem to be very good at firing at the correct time or even consistently.
When the add-on starts, it calculates the nearest future hour and creates an alarm with the when
value set to that time and then a periodInMinutes
of 60. In theory, this should work… but it does not.
There are many circumstances in which the Alarms API will stop working correctly. The easiest one to reproduce is putting your computer to sleep. If you put your computer to sleep at 10:55, when you wake up the computer at 11:15, the alarm will immediately fire. The next alarm will then be set to fire at 12:15 and all subsequent alarms will fire 15 minutes later than they are supposed to.
As a workaround, I’ve only been setting the when
value in the alarm. Then, when the alarm fires next, I recalculate the next when
value and create a new alarm.
This works, except that it still does not work properly. There have been cases (I have not been able to consistently reproduce myself) where sometimes the alarm just does not fire at all and just sits until the browser is restarted. If you query the alarms, you will see that it’s still registered, but that the scheduledTime
is in the past.
So the final workaround that I’ve been using for years now is what I like to call the “Rolex approach”. Basically the browser acts as a self-winding watch. I create a listener for any tab updates. That listener checks that the alarm exists and that the scheduledTime
value is set correctly. If it’s not, it recreates the correct alarm.
The issue I have with this is that I should not have to do all that. It causes the extension to make so many more function calls that it needs to. Depending on how active the user is, it could validate the alarm tens or even hundreds of times per minute. Plus, I don’t think this approach works will with service workers in MV3 because it’s constantly forcing the service worker to stay alive.
Is there a better workaround? Or better yet, does anyone know what causes the missed alarms so that it can be patched?