Streaming API not working when email is sent from Apex Batch

I have a Batch class that updates Last_Date__c on Project__c object in the Finish method.

I have a PushTopic ‘LastDateUpdate’ on Project__c which is fired when Last_Date__c is updated.

I’m subscribing to ‘LastDateUpdate’ on a VF page.

In the finish method of the batch, I’m also sending an email to the current user.

global with sharing class Demo_Batch implements Database.Batchable<SObject> {

    global Iterable<SObject> start(Database.BatchableContext info) {
        //Something is returned
    }

    global void execute(Database.BatchableContext info, List<SObject> scope) {
        //stuff happens here
    }

    global void finish(Database.BatchableContext info) {
        update project;
        Messaging.sendEmail(EmailTemplate.createEmail());
    }

}

I don’t receive a Push Notification whenever an email is sent (there are no errors here and email is sent successfully). So I commented the Messaging.sendEmail(EmailTemplate.createEmail()); line and ran the batch again. I was able to receive Push Notifications.

Is there a limitation I’m not aware of? Please help!

Answer

My assumption is that you can’t send an email in the same transaction as Streaming API.

So this is my workaround:

public with sharing class QueueEmail implements Queueable {

    public Void execute(QueueableContext context) {
        Messaging.sendEmail();
    }
}

Finish method:

global void finish(Database.BatchableContext info) {
     update project;
     System.enqueueJob(new QueueEmail());
}

Attribution
Source : Link , Question Author : d_k , Answer Author : d_k

Leave a Comment