Categories
Apex Salesforce

Using Platform Events with Queueable Apex

Scenario:- How to call Queueable Apex inside platform events 

Step1:- Have a button on SFDC UI to call the “Apex Handler”

QueueableButton
Queueable Apex

Step2:- “Apex Handler” will call Platform Event

         //calling PE with the required params
        Demo_Platform_Event__e peObj = new Demo_Platform_Event__e( EndPoint_Url__c = endPointUrl );
        Database.SaveResult sr = EventBus.publish(peObj);       
        if (sr.isSuccess()) {                        
            System.debug('Successfully published Demo_Platform_Event__e Event.');
        } else {
            for(Database.Error err : sr.getErrors()) {
                System.debug('Error returned on Publishing Demo_Platform_Event__e Event: ' +
                                err.getStatusCode() +
                                ' - ' +
                                err.getMessage());                     
            }
            
        }

Step3:- “Platform Event” when called will launch the “Trigger”

Setup > Platform Events > New Platform Events

Add Trigger and Custom Fields as shown below:-

PlatformEvent
PlatformEvent

Step4:- Inside “Trigger” call the Queueable Apex

Here we can bulkification trigger to a batch size of 50, as supported by Queueable

trigger demoTriggerHandler on Demo_Platform_Event__e(after insert) {
     List<String> peListItems = new List<String>(); 
     Integer  counter = 0;
         for(Demo_Platform_Event_e__e peObj : peListItems) {
            counter++;
            System.debug('Counter = '+ counter);    
            if (counter >=  50) { //taking batch size of 50 clinics as supported by Queueable Apex
                break;
            }
             else{
                  peListItems.add(peObj);
            }
            //platform event bus
            EventBus.TriggerContext.currentContext().setResumeCheckpoint(peObj.ReplayId);           
        }    
        // instantiate a new instance of the Queueable class and pass params
        calloutHelper objCallout = new calloutHelper(peList);
        ID jobID = System.enqueueJob(objCallout);
        System.debug('jobID = '+ jobID);
}

Step5:- “Queueable Apex” will initiate “HTTP callout” to the external system.

       //Sample HTTP callout 
       Http http = new Http(); 
       HttpRequest req = new HttpRequest(); 
       req.setEndpoint(endPointUrl); 
       req.setMethod('PUT'); 
       req.setBody(inputData); 

       req.setHeader('content-type', 'application/json'); 
       req.setHeader('Accept', 'application/json'); 
       HTTPResponse res = http.send(req); 
       outputMap.put(KEY_RESULTS, res.getBody()); 
       Integer statusCode = res.getStatusCode(); 
       System.debug('code ='+statusCode); 
       if(statusCode == 200){ //do logic on the success } 
       else{ //throw exception }

More on Queueable Apex code base 

 

Leave a Reply

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