Using Platform Events with Queueable Apex – User friendly Tech help
n
Scenario:- How to call Queueable Apex inside platform events
n
Step1:- Have a button(can be vlocity action or vlocity Omniscript guided flow) on SFDC UI to call the “Apex Handler”
n Queueable Apexn
Step2:- “Apex Handler” will call Platform Event
n
//calling PE with the required paramsn Demo_Platform_Event__e peObj = new Demo_Platform_Event__e( EndPoint_Url__c = endPointUrl );n Database.SaveResult sr = EventBus.publish(peObj); n if (sr.isSuccess()) { n System.debug('Successfully published Demo_Platform_Event__e Event.');n } else {n for(Database.Error err : sr.getErrors()) {n System.debug('Error returned on Publishing Demo_Platform_Event__e Event: ' +n err.getStatusCode() +n ' - ' +n err.getMessage()); n }n n }
n
Step3:- “Platform Event” when called will launch the “Trigger”
n
Setup > Platform Events > New Platform Events
n
Add Trigger and Custom Fields as shown below:-
n PlatformEventn
Step4:- Inside “Trigger” call the Queueable Apex
n
Here we can bulkification trigger to a batch size of 50, as supported by Queueable.
n
trigger demoTriggerHandler on Demo_Platform_Event__e(after insert) {n List peListItems = new List(); n Integer counter = 0;n for(Demo_Platform_Event_e__e peObj : peListItems) {n counter++;n System.debug('Counter = '+ counter); n if (counter >= 50) { //taking batch size of 50 Id's as supported by Queueable Apexn break;n }n else{n peListItems.add(peObj);n }n //platform event busn EventBus.TriggerContext.currentContext().setResumeCheckpoint(peObj.ReplayId); n } n // instantiate a new instance of the Queueable class and pass paramsn calloutHelper objCallout = new calloutHelper(peList);n ID jobID = System.enqueueJob(objCallout);n System.debug('jobID = '+ jobID);n}
n
Step5:- “Queueable Apex” will initiate “HTTP callout” to the external system.
n
//Sample HTTP callout n Http http = new Http(); n HttpRequest req = new HttpRequest(); n req.setEndpoint(endPointUrl); n req.setMethod('PUT'); n req.setBody(inputData); nn req.setHeader('content-type', 'application/json'); n req.setHeader('Accept', 'application/json'); n HTTPResponse res = http.send(req); n outputMap.put(KEY_RESULTS, res.getBody()); n Integer statusCode = res.getStatusCode(); n System.debug('code ='+statusCode); n if(statusCode == 200){ //do logic on the success } n else{ //throw exception }
n
More on Queueable Apex code base