Wednesday, 12 July 2017

How to send email for every 30 minutes with batch apex in Business hours

Below is the code to send email for every 30 minutes with a batch class.


global class OpportunityNotifierBatch implements Database.Batchable<sObject>,Database.Stateful, Schedulable {
    public Map<Id,String> emailmap{get;set;}
    global void scheduleMe() {      
        system.schedule('OpportunityNotifierBatch 1', '0 00 * * * ?', new OpportunityNotifierBatch());
        system.schedule('OpportunityNotifierBatch 2', '0 30 * * * ?', new OpportunityNotifierBatch());      
    }
    global void execute(SchedulableContext sc){
        if(isBusinessHour()){
        OpportunityNotifierBatch batch=new OpportunityNotifierBatch();
        ID batchprocessid=Database.executeBatch(batch);
        }
    }
    global Database.QueryLocator start(Database.BatchableContext BC) {
        Datetime d = datetime.now().addMinutes(-30);
        emailmap=new Map<Id,String>();
        String query = 'select id, createddate, name ,owner.email from Opportunity where createddate < :d LIMIT 10';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> scope) {
        for(Opportunity w : scope){          
            emailmap.put(w.Id,w.owner.email);        
        }
    }  
    global void finish(Database.BatchableContext BC) {      
    //finish will be called after last batch finishes
        for(Id i:emailmap.keySet())
            sendEmail(i,emailmap.get(i));
    }
    public void sendEmail(Id wId,String email){
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        List<String> emaillist=new List<String>();
        emaillist.add(email);
        message.toAddresses = emaillist;
        //message.ccAddresses = new List<String> {label.Off_Boarding_CC_Email_addresses};
        message.subject = 'Reminder: You have a new record';
        message.plainTextBody = 'Please review the following Work Request\n'+
            'Detail link :'+ URL.getSalesforceBaseUrl().toExternalForm()+'/'+wId;
        Messaging.SingleEmailMessage[] messages =
            new List<Messaging.SingleEmailMessage> {message};
                Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        if (results[0].success) {
            System.debug('The email was sent successfully.');
        } else {
            System.debug('The email failed to send: '
                         + results[0].errors[0].message);
        }
    }
    public boolean isBusinessHour(){
        // Get the default business hours
        BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];
        DateTime targetTime=DateTime.now().addMinutes(-30);
        // Find whether the time is within the default business hours
        Boolean isWithin= BusinessHours.isWithin(bh.id, targetTime);
        return isWithin;
    }
}


In Debug> open execute anonymous window, execute the following line,

new OpportunityNotifierBatch().scheduleMe();

The above line schedules your batch class and for every 30 minutes opportunity owners will be notified with an email.
The maximum emails a batch class can process at a time is 10.
Note the method isWithin(Id,time) will return true is the present time is in business hour.


No comments:

Post a Comment