function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Karel MichekKarel Michek 

How to cleanup CustomNotification sent by Page reference

Hi, I have developed a custom notification in Apex using a page reference to an Aura component, and it works fine (user clicks on notifications under the Bell icon top right and get forwarded to the aura component). But I cannot find a way how to cleanup old notifications, is there a way, please? The system doesn't cleanup automatically, it probably must be done programmatically.
My apex code: 
Messaging.CustomNotification notification = new Messaging.CustomNotification();
notification.setTitle('...');
notification.setBody('...');
notification.setSenderId(UserInfo.getUserId());
notification.setNotificationTypeId([SELECT Id FROM CustomNotificationType WHERE DeveloperName ... LIMIT 1].Id);
User user = [SELECT Id FROM User WHERE ... LIMIT 1];
Map<String, Object> pageRef = new Map<String, Object>{
        'type' => 'standard__component',
        'attributes' => new Map<String, Object>{
                'componentName' => 'c__...'
        },
        'state' => new Map<String, Object>{
                'c__jobId' => ...,
                'c__userId' => ...
        }
notification.setTargetPageRef(JSON.serialize(pageRef));
notification.send(new Set<String>{
        user.Id
});

then the Aura component: 
implemets="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,lightning:isUrlAddressable">
Shri RajShri Raj
you need a batch job
global class CleanUpCustomNotificationBatch implements Database.Batchable<SObject> {
    global final Datetime CUT_OFF_DATE = System.today().addDays(-30);

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([
            SELECT Id
            FROM CustomNotification
            WHERE CreatedDate < :CUT_OFF_DATE
        ]);
    }

    global void execute(Database.BatchableContext bc, List<SObject> scope) {
        delete scope;
    }

    global void finish(Database.BatchableContext bc) {
    }
}


This batch job deletes the CustomNotification records that were created more than 30 days ago (this is defined in the CUT_OFF_DATE constant). You can schedule the batch job to run daily or weekly using a Scheduled Apex class, or you can run it manually by calling it in the Developer Console.
Karel MichekKarel Michek
Hi, thanks for your answer. Messaging.CustomNotification doesn't seem to be an sObject, when I try SELECT Id FROM CustomNotification I get "ERROR at Row:1:Column:16, sObject type 'CustomNotification' is not supported." If it's an sObject then maybe it's access needs to be enabled somehow?