Scheduling a Delayed Task That Outlives Your Service Worker
The feature request was one sentence: "send the welcome tip five minutes after install, not immediately". The implementation took twenty minutes. Making it survive a worker restart took an afternoon, because "five minutes later" is a promise the browser is not obligated to keep. Here is the smallest design that does keep it. What you need to know first: an alarm is a wakeup hint, not a job. The…
The feature request was simple: send a welcome tip five minutes after installation, not immediately. The implementation took just 20 minutes. Making the task survive a service worker restart took longer, an afternoon, because "five minutes later" is not a guarantee from the browser. Here is the smallest design that accomplishes this.
First, understand that an alarm is a wakeup hint, not a job. The job resides in storage; the alarm only signals when to check. To model the task as data, make it serializable. No closures, class instances, or function references are allowed. Define a DelayedTask interface with an ID, dueAt timestamp, type, and payload.
Persist the task before scheduling it. Store it in local storage, then arm the alarm. If the worker restarts between these steps, the recovery process can still find an unscheduled task. Use a single key for the entire queue to keep writes efficient, and one alarm per task to keep firing times independent.
Make the executor idempotent by claiming the task before running it. Alarms can fire multiple times, and a restart might create a second executor. Before running the task, check if it's already running. If so, delete it from the queue. This prevents repeating the task after a crash.
Listen for alarms using chrome.alarms.onAlarm.addListener. Ignore alarms that don't start with 'task:', as they are not related to your task. Claim the task using the alarm's name, and if it exists, run the task.
On startup and installation, rebuild the alarms from the queue since Chrome doesn't guarantee their survival. Iterate through the queue, and for each task with a dueAt time in the past, claim it and run the task if it's still available.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to