function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Priya AakankshaPriya Aakanksha 

If now time - lead created time is greater than 2 hours, AND Last Activity date is NULL, then trigger the Alert Email.

If now time - lead created time is greater than 2 hours, AND Last Activity date is NULL, then trigger the Alert Email.

I wrote batch class its showing complete but not getting any mails
here is my code -----
=============================
global class Lead_Escalation implements database.Batchable<sobject>,schedulable{
    
    global Id userId;
    global database.QueryLocator start(database.BatchableContext bc){
      string  query;
         string a ='Website' ;
         string b ='Phone' ;
        Datetime d2= system.now().addhours(32);
    
       if(!test.isRunningTest()){
       query='select id,Name,Owner.ID,LastModifiedDate,owner.firstname,CREATEDDATE,owner.name,owner.lastname,Owner.Email,LeadSource,LASTACTIVITYDATE FROM lead where (CREATEDDATE=:d2 AND LASTACTIVITYDATE= Null AND(LeadSource=:a OR LeadSource=:b))';
       }else{
       query='select id,Name,Owner.ID,LastModifiedDate,owner.firstname,CREATEDDATE,owner.name,owner.lastname,Owner.Email,LeadSource,LASTACTIVITYDATE FROM lead limit 1';
            }
            
            return database.getQueryLocator(query);
      }
    
        global void execute(database.BatchableContext bc,list<lead>ldlist){
        emailtemplate LeadEscalationTemplate=[SELECT Id, Subject FROM EmailTemplate WHERE name='LeadEscalationTemplate'];
            
            list<user> userlist=[select id,name,isactive,profileid,profile.name,email,userrole.name from user where userrole.name = 'National Sales Head - Retail' AND isactive=true];
   
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
     
        list<task> tklist=new list<task>();
            
            list<string>toadd=new list<string>();
            for(user us:userlist){
            toadd.add(us.email);
            }
        for(lead l:ldlist){
           
            {
                if(test.isRunningTest()  || l.CREATEDDATE.hour() > 2){
                
                toadd.add(l.owner.email);
                Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
                     
                message.setSubject('Reminder :Enquiry for '+'l.name' + ' to be acted on.');
                    List<String> sendTo = new List<String>();
                    sendTo.add(tklist[0].Owner.Email);
                    
                  message.setToAddresses(sendTo);
                  message.setccaddresses(toadd);
          //      mail.settoaddresses(toadd);
                  message.setTargetObjectId(l.ownerid); 
                  message.setWhatId(l.id);
                  message.setBccAddresses(new string[]{'priyaaakanksha28@gmail.com'});
                  message.setsenderdisplayname('kk');
                  message.setSaveAsActivity(false);
                  message.setTemplateID(LeadEscalationTemplate.id);
        //        message.setHtmlBody(body);
                  mails.add(message);
                
                
               
               task tasks=new task();       
               tasks.WhoId=l.id;
               tasks.OwnerId=l.ownerid;
                
               tasks.Subject='Reminder';
               tasks.Description='It has been two hours since this lead is created and no activity is created. Please contact the customer';
               tasks.Task_Info__c='ALERT';
               tasks.Priority='Medium';
               tasks.Status='Open';
          //     tasks.Assigned To='Owner';
                  tklist.add(tasks);
   
     } 
            }                                                                                      
                                               
        if(!test.isRunningTest()){
            if(mails.size() > 0){
                Messaging.sendEmail(mails); 
            }
            if(tklist.size() > 0){
                insert tklist;
            }
            
        }
        
    }
   }
    global void finish(database.BatchableContext bc){
        
    }
    global void execute(SchedulableContext sc) {
        Lead_Escalation b2 = new Lead_Escalation();
        ID batchprocessid = Database.executeBatch(b2,50);  
    }
    
}
==============================================
Please help me out from this issue that i m not getting any mails
Neha AggrawalNeha Aggrawal
Hi Priya,

Please search for "Apex Jobs" in setup and see if any batches were processed. Like below:
User-added image

If  totalbatches shows zero, your query might not be returning any results. 

Hope this helps.
Thanks and Regards, 
Neha Aggrawal
www.initaura.com - Everything Salesforce (https://www.initaura.com)