How to schedule periodic task in PWA service worker

Viewed 574

I would like to schedule a periodic task in my PWA, then I can display notifications at some specific time each day.

I tried the Notification API: https://web.dev/notification-triggers/, it seems working. However, according to the document, it still requires to setInterval in the App's page context, e.g

setInterval(() => navigator.serviceWorker.getRegistration().then(reg=>{
  if (!reg) {
    return
  }
  reg.showNotification('test', {
      tag: 'test-tag',
      body: 'This notification was scheduled 1min ago',
      showTrigger: new TimestampTrigger(new Date().getTime() + 60 * 1000),
    });
  }), 60 * 1000)

It is not my ideal solution, if I close my app, the notifications will not be triggered.

Then I tried the periodicSync API: https://web.dev/periodic-background-sync/, e.g

await registration.periodicSync.register('periodic-notification', {
  minInterval: 60*1000
});

according to my test, the service worker can receive the periodicSync event if I manually trigger them in dev-tool->Application->Service Workers->Periodic Sync button. But what I am expecting is getting the periodicSync event every 1min. According to the doc, seems it is related with the site-engagement, then it is not a real periodic task.

Any ideas to resolve this issue? Thank you!

0 Answers
Related