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
Sean BarczynskiSean Barczynski 

Trouble with scheduled apex

Hello,

I'm having some trouble getting scheduled Apex classes to run consistently and correctly. 

I have one that sends out emails every morning to clients who have meetings in 2 days.  This class is scheduled to run every morning (including the weekends).  Is there any reason it would run for a few days and then just stop?  If it experiences an exception, does that then prevent it from running the following day?  Do they run on weekends?  I have yet to see one run on the weekends, but that may just be a coincidence.  In the list of scheduled classes, it always says that they run, but no emails are being sent...

The second scheduled class I have is supposed to update all contacts and, in turn, trigger my Contact update triggers.  This class seems to be running correctly, but none of the Contact onUpdate triggers are running correctly.  However, when I edit an individual Contact, the triggers run correctly.

 
Gaurav Jain 7Gaurav Jain 7
If you need to check on the daily(5 working days) basis, you need to go with the apex Schedule class.
Sean BarczynskiSean Barczynski
Meeting Reminders class:
 
global class MeetingReminderEmailScheduled Implements Schedulable {

	global void execute(SchedulableContext sc)
	{
		MeetingReminderEmailScheduled();
	}
	
	public void MeetingReminderEmailScheduled()
	{
		List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
		
		Date dateToday = Date.newInstance(System.today().year(),System.today().month(),System.today().day());
		
		List<Event> eventList = [select Id,  
                                    WhatID, 
                                    WhoID,
                                    StartDateTime, 
                                    ActivityDateTime,
                                    FSTR__Sub_Type__c,  
                                    Status__c, 
                                    Tax_Preparation__c,
                                    Financial_Plan_Update__c, 
                                    IPS_Updated__c, 
                                    Dont_Send_Reminder__c,
                                    Tax_Plan__c
                               from Event];
                               
        Set <Id> whatIdSet = new Set <Id> ();

	    for(Event e : eventList)
	    {
	        if(e.WhatId != null)
	        {
	            whatIdSet.add(e.WhatId);
	        }
	    }
                               
        Map<ID, Account> accountMap = new Map<ID, Account>([select Id, 
												   Name, 
                                                   Last_Info_Update__c,
                                                   Last_Review_Meeting__c, 
                                                   Last_FP_Update__c, 
                                                   Last_IPS_Update__c,  
                                                   Last_Tax_Planning_Meeting__c,
                                                   Greeting__c, 
                                                   Number_of_Attempts_to_Schedule_Review__c,
                                                   Number_of_Attempts_to_Schedule_TaxPlan__c,
                                                   Number_of_Attempts_to_Schedule_TaxPrep__c,
                                                   Last_Tax_Prep_Meeting__c
                                              from Account 
                                             Where Id in :whatIdSet]);
                               
    	List<Contact> contactList = [select Id,
    									Name,
    									AccountId,
    									Primary_Email_Address__c,
    									Email,
                                        FirstName,
                                        ACTDDEV__Nickname__c,
                                        Include_on_Correspondence__c,
                                        Primary__c
                                   from Contact
                                  Where Include_on_Correspondence__c = :TRUE];
                                  
    	List<FSTR__PCE_Team_Member__c> clientTeamList = [select Id,  
                                                            FSTR__Client__c,
                                                            FSTR__Team_Member__c, 
                                                            FSTR__Team_Role__c
                                                       from FSTR__PCE_Team_Member__c
                                                      Where FSTR__Client__c in :whatIdSet
                                                        And FSTR__Team_Role__c = :'Relationship Manager'];
    	
    	List<User> userList = [select id, 
	    							  Name, 
	    							  Email, 
	    							  Title, 
	    							  CompanyName, 
	    							  Phone 
	    						 from User];
    	
    	List<OrgWideEmailAddress> owaList = [select id, 
    											DisplayName, 
    											Address 
    									   from OrgWideEmailAddress];
    	
    	User sdli = [select Id, Name, Email from User where Email = :'sdli@ag.com' LIMIT 1];
    	
    	
		List <Task> TasksToCreate = new List <Task> ();
    	
    	OrgWideEmailAddress owa;
    	
    	for(Integer o=0;o<=owaList.size()-1;o++)
    	{
    		if(owaList[o].Address == 'sdli@ag.com')
    		{
    			owa = owaList[o];
    		}
    	}
    	
    	for(Integer e=0;e<eventList.size();e++)
    	{
    		String dayOfWeek = eventList[e].StartDateTime.format('EEEE');
    		
    		if(eventList[e].WhatId != NULL && eventList[e].FSTR__Sub_Type__c != 'Internal/No Email' && eventList[e].Status__c == 'Scheduled' && Date.newInstance(eventList[e].ActivityDateTime.year(), eventList[e].ActivityDateTime.month(), eventList[e].ActivityDateTime.day()) == dateToday.addDays(2))
    		{
    			Integer contactCount = 0;
    			Account a1 = accountMap.get(eventList[e].WhatId);
    			User RM;
    			
    			for(Integer t=0;t<clientTeamList.size();t++)
    			{
    				if(clientTeamList[t].FSTR__Client__c == eventList[e].WhatId)
    				{
    					for(Integer u=0;u<userList.size();u++)
    					{
    						if(userList[u].Id == clientTeamList[t].FSTR__Team_Member__c)
    							RM = userList[u];
    					}
    				}
    			}
    			
    			String meetingType = '';
    					
    			if(eventList[e].FSTR__Sub_Type__c == null)
    			{
    				meetingType='';
    			}
				else if(eventList[e].FSTR__Sub_Type__c == 'Client Review Meeting')
				{
					meetingType = 'Financial Review Meeting';
					
					if(eventList[e].Tax_Plan__c)
						meetingType += ' & Tax Planning Meeting';

					if(eventList[e].Tax_Preparation__c)
						meetingType += ' & Tax Preparation Meeting';
				}
				else if(eventList[e].Tax_Plan__c && eventList[e].FSTR__Sub_Type__c != 'Tax Planning Meeting')
				{
					meetingType = eventList[e].FSTR__Sub_Type__c + ' & Tax Planning Meeting';
				} 
				else if (eventList[e].Tax_Preparation__c && eventList[e].FSTR__Sub_Type__c != 'Tax Preparation Meeting')
				{
					meetingType = eventList[e].FSTR__Sub_Type__c + ' & Tax Preparation Meeting';
				}
				else
				{
					meetingType = eventList[e].FSTR__Sub_Type__c;
				}
    			
    			for(Integer c=0;c<contactList.size();c++)
    			{
    				String[] toAddresses = new String[] {};
    				
    				if(contactList[c].AccountId == eventList[e].WhatId && contactList[c].Include_on_Correspondence__c == TRUE && contactList[c].Email != NULL)
    				{
    					contactCount++;
    					
    					String greeting;
    		
    					toAddresses.add(contactList[c].Email);
    					
    					if(contactList[c].ACTDDEV__Nickname__c != NULL)
    						greeting = contactList[c].ACTDDEV__Nickname__c;
    					else
    						greeting = contactList[c].FirstName;
    					
						Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		                mail.setOrgWideEmailAddressId(owa.Id);
		                mail.setToAddresses(toAddresses);
		  				mail.setSubject('Your Upcoming Meeting');
		  						
		  				String body =  'Hi ' + greeting + ',';
		  					   body += '<p>I am writing to confirm your upcoming appointment:</p>';
		  				       body += '<p style="margin-left: .5in;">' + meetingType + '<br>' + eventList[e].StartDateTime.format('EEEE, MMMM d') + ' at ' + eventList[e].StartDateTime.format('h:mm a') + ' ET' + '</p>';
		  				       body += '<p>If you need to cancel or reschedule this meeting, please let me know by replying to this email or calling me at ---.</p>';
		  				       body += '<p>Thank you,</p>';
		  				       
		  				mail.setHtmlBody(body);
		  										   
		  				mails.add(mail);
		  									
		  				String newBody;
		  				newBody = body.replace('<p>','\n');
		  				newBody = newBody.replace('<p style="margin-left: .5in;">','\n');
		  				newBody = newBody.replace('</p>','\n');
		  				newbody = newBody.replace('<br>','\n');
		  						
		  				for(Integer ea=0;ea<toAddresses.size();ea++)
		  				{
			  				TasksToCreate.add(new Task(	OwnerID = sdli.Id,
			                          					Subject = 'Email: Your Upcoming Meeting!',
			                                  			Description = 'To: ' + toAddresses[ea] + '\n' + newBody + '\n',
			                                           	WhatID = eventList[e].WhatId,
			                                           	ActivityDate = date.today(),
			                                           	Status = 'Completed',
			                                           	Priority = 'Normal'));
		  				}
    				}
    			}
    			
    			if(contactCount==0)
    			{
    				String[] toAddresses = new String[] {};
    				toAddresses.add(RM.Email);
    				Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
	                mail.setToAddresses(toAddresses);
	  				mail.setSubject('Upcoming Event Email');
	  				mail.setReplyTo('noReply@ag.com');
  					mail.setSenderDisplayName('System Notice');
	  						
	  				String body  = '<p>A reminder email was not sent for the below meeting because the Household does not have any contacts with a valid email address who are to be included on correspondence .  Please notify Susan to update this client\'s information accordingly and email them a reminder.</p><p><em>Please note:  This task may be able to be completed en masse by completing the latest Data Audit sheets.</em></p>';
	  				       body += '<p style="margin-left: .5in;">' + a1.Name + '<br>' + meetingType + '<br>' + eventList[e].StartDateTime.format('EEEE, MMMM d') + ' at ' + eventList[e].StartDateTime.format('h:mm a') + ' ET' + '</p>';
	  				mail.setHtmlBody(body);
	  										   
	  				mails.add(mail);
    			}
    		}
    	}
    	
    	if(TasksToCreate != null && TasksToCreate.size()>0)
        	insert TasksToCreate; 
        	
        if(mails != null && mails.size()>0)
        	Messaging.sendEmail(mails);
	}
}

Update All Contacts class:
 
global class UpdateAllContacts Implements Schedulable {

	global void execute(SchedulableContext sc)
	{
		UpdateAllContacts();
	}
	
	public void UpdateAllContacts()
	{
		List<Contact> contactList = [select Id,
    									Name,
    									AccountId,
    									Primary_Email_Address__c,
    									Email,
                                        FirstName,
                                        ACTDDEV__Nickname__c,
                                        Include_on_Correspondence__c,
                                        Increment__c,
                                        Primary__c
                                   from Contact];
                                   
        List<OrgWideEmailAddress> owaList = [select id, 
    											DisplayName, 
    											Address 
    									   from OrgWideEmailAddress];
        
        for(Integer i=0;i<contactList.size();i++)
        {
        	if(contactList[i].Increment__c == null)
        		contactList[i].Increment__c = 0;
        	else
        		contactList[i].Increment__c++;
        }
                                   
        
        
        try 
        {
		    update contactList;
		} 
		catch(Exception e) 
		{
		    System.debug('The following exception has occurred: ' + e.getMessage());
		    
		    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
		    OrgWideEmailAddress owa;
		    
		    for(Integer o=0;o<=owaList.size()-1;o++)
	    	{
	    		if(owaList[o].Address == 'sdli@ag.com')
	    		{
	    			owa = owaList[o];
	    		}
	    	}
		    
		    String[] toAddresses = new String[] {};
		    toAddresses.add('sbki@ag.com');
		    
		    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setOrgWideEmailAddressId(owa.Id);
            mail.setToAddresses(toAddresses);
  			mail.setSubject('Error updating all contacts');
  						
  			String body =  e.getMessage();
  			mail.setHtmlBody(body);
  										   
  			mails.add(mail);
  			
        	Messaging.sendEmail(mails);
		}
	}
}
Sean BarczynskiSean Barczynski
I used the schedulable class and used the Schedule Apex feature and it worked for a few days, then stopped.  I'm not sure why.  Please advise...