How to send a web notification at a specific time

You can use the Push API to send timely notifications from your website (the notifications are delivered even when the user is not on your website). If you use Pushpad, a service for web push, it is very simple to set the time when the notification must be delivered. The following example shows how to create a button to create a reminder.

On the client side, you can use the Javascript SDK to subscribe the user to the notifications and send a request to your server to create the reminder/notification:

// when the user clicks the button
$('button#create_reminder').on('click', function () {
 // make sure that the user is subcribed to push notifications
 pushpad('subscribe', function (isSubscribed) {
   if(isSubscribed) {
     // let's schedule the notification from the backend
     fetch('/create_reminder', {
       method: 'POST',
       body: 'event_id=' + $('button#create_reminder').data('event')
     });
   } else {
     alert('You need to allow push notifications from this website in order to receive the reminder.');
   }
 }, {
   uid: userID, // an ID for the current user (e.g. the user primary key in your database)
   uidSignature: '...' // learn more: https://pushpad.xyz/docs/identifying_users
 });
});

On your server, you can optionally save the reminder in your database and create the notification that will be delivered in the future by Pushpad. You can use the Pushpad libraries, which are available for most languages. For example, if you use Ruby:

def create_reminder
  @event = Event.find(params[:event_id])
  notification = Pushpad::Notification.new({
    body: "Reminder: #{@event.name}",
    send_at: (@event.happens_at - 1.hour)
  });
  notification.deliver_to current_user.id
  // you may also want to save the tuple (user_id, event_id, notification_id) in your database 
  // in case you need to cancel the notification later or you need to find the reminders for a user
end

An alternative approach would be to save the reminder only in your database, without scheduling the notifications. Then run a cron job every minute which queries the database and sends the notifications at the correct time. Another alternative would be to use a background worker like Sidekiq which supports scheduled jobs.

Leave a Reply

Your email address will not be published. Required fields are marked *