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
Patti AbeyratnePatti Abeyratne 

Number of Contact - Schedule job

Can anybody correct this code or give me a code which summerize number of contacts on account?

global class scheduledCalculatebookings implements Schedulable {
   global void execute(SchedulableContext sc) {
       /* System.debug('Schedule');
      calculateBooking b = new calculateBooking();
      database.executebatch(b);*/
  
  
  
  
   Map<Id, List<Contact>> AcctContactList = new Map<Id, List<Contact>>();
    Set<Id> AcctIds = new Set<Id>();   
    List<Account> AcctList = new List<Account>();
    List<Account> AcctOld = new List<Account>();
    List<Contact> ConList = new List<Contact>();
    AcctOld = [SELECT Id FROM Account];
   
    for(Account old : AcctOld)
    {
        AcctIds.add(old.Id);
       
    if(AcctIds.size() > 0){
        ConList = [SELECT Id, AccountId FROM Contact WHERE AccountId IN : AcctIds];
       
        for(Contact Con : ConList) {
            if(!AcctContactList.containsKey(Con.AccountId)){
                AcctContactList.put(Con.AccountId, new List<Contact>());
            }
            AcctContactList.get(Con.AccountId).add(Con);     
        }                          
       
        System.debug('Account Id and Contact List Map is ' + AcctContactList);
           
        AcctList = [SELECT Open_Activity_Count_c__c FROM Account WHERE Id IN : AcctIds];
       
        for(Account Acc : AcctList) {
            List<Contact> ContList = new List<Contact>();
            ContList = AcctContactList.get(Acc.Id);
            Acc.Open_Activity_Count_c__c = ContList.size();
        }   
       
        System.debug('Account List is ' + AcctList);
        update AcctList;  
     }

     }
   
  
       
    //Send an email to the User after your batch completes
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {'test@gmail.com'};
    mail.setToAddresses(toAddresses);
    mail.setSubject('Apex Batch Job Calculate Bookings');
    mail.setPlainTextBody('The batch Apex job processed ');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }
}
Ankit AroraAnkit Arora
Not sure what exactly you want, but how about fetching all contacts related to accounts like this :

List<Account> accLst = [select id, (select id from contacts) from Account] ;

Will this helps?
Patti AbeyratnePatti Abeyratne
Hi Ankit,  Thanks for the reply. What I want is to calculate the number of contacts on account and write that number to a field in account.
Ankit AroraAnkit Arora
So my above query will work, this will return you all the contacts related to each account in list. You can get the size of the list and update it in account.