Thursday, June 2, 2022

How to Fire Platform Events from Batch Apex

Today we will discuss about, How to Fire Platform Events from Batch Apex

Batch class needs to implement "Database.RaisesPlatformEvents" interface in order to fire platform event.

global class SK_AccountProcessBatch implements Database.Batchable<sObject>,Database.RaisesPlatformEvents{

   //batch logic

}

below is the sample code for the same:-

global with sharing class PlatformEventRaise implements Database.Batchable<SObject>, Database.RaisesPlatformEvents{

    // class implementation

    global Database.QueryLocator start(Database.BatchableContext BC){

        return Database.getQueryLocator('Select Id ,Name,Rating,Industry, BillingAddress,BillingStreet,BillingCity, BillingCountry, BillingPostalCode,BillingState,Phone from Account  where BillingStreet!=NULL');

    }

    global void execute(Database.BatchableContext BC, List<sObject> scope){

         List<Account> accs =(List<Account>) scope ; 

        List<Cloud_News__e> cnewList = new List<Cloud_News__e>();

        for(Account a : accs){

            // Create an instance of the event and store it in the newsEvent variable

            Cloud_News__e newsEvent = new Cloud_News__e(

                Location__c=a.BillingStreet, 

                Urgent__c=true, 

                News_Content__c=a.BillingStreet);

              cnewList.add(newsEvent) ;

         }      

// Call method to publish events

        Database.SaveResult sr =  EventBus.publish(cnewList);

        // Inspect publishing result 

        if (sr.isSuccess()) {

            System.debug('Successfully published event.');

        } else {

            for(Database.Error err : sr.getErrors()) {

                System.debug('Error returned: ' +  err.getStatusCode() +' - ' + err.getMessage());

            }

        }       

    }    

    global void finish(Database.BatchableContext BC){

    }

}