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
Meenakshi sinhaMeenakshi sinha 

batch apex explanation

Hi friends
I have to work on batch apex code .
I have mentioned the ​​entire code.

The scenario is : ​If sales lead does not follow the contacts in 2 days then it is assigned to another user.​
In contact object, custom field called days_since_last_activity. If greater than 2 then records are assigned to another user and email sent.
This is my understanding.

global class UpdateAllContacts implements Database.Batchable<sObject>
 {
   
     //This is the query that is passed to the execute method.  It queries all of the Contacts who have passed the protected period.
    
     String query = 'Select Id, OwnerId FROM Contact WHERE Days_Since_Last_Activity__c > 2';
   
     global database.queryLocator start(Database.BatchableContext BC)
     {
        return database.getQueryLocator(query);
     } //close start method
   
     global void execute(Database.BatchableContext BC, list <Contact> scope)
     {
   
        List <Task> taskList = new List<Task>();
     // Iterate through the whole query of Contacts.
     // Create a Task that's associated with each Contact.  This resets the Days Since Last Activity formula field.
     for(Contact c : scope)
     {
               c.OwnerId = '00590000003s0MYAAY';
               Task tsk = new Task();
               tsk.WhoId = c.Id;
               tsk.ActivityDate = System.today();
               tsk.Status = 'Completed';
               tsk.Subject = 'Ownership Transferred';
   
               taskList.add(tsk);
    
    } //close for-loop
   
     try
     {
        insert taskList;
     }
     catch(exception e)
     {
        System.debug('Tasks not inserted: ' + e);
     }
   
     try
    {
        update scope;
     }
     catch (system.dmlexception e)
     {
        System.debug('Scope not updated: ' + e);
     }
   
     } //close execute method
   
   
     global void finish(Database.BatchableContext BC)
     {
   
     AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob
                       where Id =:BC.getJobId()];
   
     // Create and send an email with the results of the batch.
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   
     mail.setToAddresses(new String[] {a.CreatedBy.Email});
     mail.setReplyTo('batch@mycompany.com');
     mail.setSenderDisplayName('Batch Processing');
     mail.setSubject('Contact Update ' + a.Status);
     mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems + ' batches with ' + a.NumberofErrors + ' failures.');
   
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     } //close finish method class
    
} //close global class



global class ScheduleUpdateContacts implements Schedulable
{
    global void execute(SchedulableContext SC)
    {
        UpdateAllContacts uac = new UpdateAllContacts();
       
        database.executebatch(uac);
       
    } //close execute method
   
} //close class

I want to know:
a) If user_A has 1000 contacts under him and he does not follow up in 2 days then how all 1000 records get assigned to another user?
    are we hardcoding the userID
b) are we assigning all 1000 records to single user?
c) ​​​​​​​how do I check if say User_B has been assigned all 1000 records because user_A did not follow since last 2 days?
d) does the system admin transfer ownership to another user:?

please help me out in understandng this.

thanks
meenakshi​​​
Abhishek BansalAbhishek Bansal
Hi Meenakshi,

Clearing out your queries :
  1. Hardcoding any Id in Apex is not feasible so this must be know to you that, To which User you are assigning all contacts.This can be done on the basis of Profiles .For ex : If User A belonging to Profile A does not follow up in 2 days than all the contacts should be assigned to either a particular User or any User belonging to Profile B. So on the basis of Profile or User Name you can query and get your UserId.
  2. Yes, With your code it is pretty clear that you are assigning all the records to a sigle user. If you properly follow answer to question 1 than this Case will automatically be sorted out.
  3. Since you have created a Batch and scheduler class so you have to schedule this scheduler class to run your batch on the daily basis or as per your requirement. You can easily monitor your batch in Apex Jobs and form there you will get complete information about the total no. of batches processed and how many are successful or Failed.
  4. Ownership can be transfeered by either record owner or Admin. Since you are updating many records so it will be highly possible that owners will differ so i would suggest you to schedule this batch form System Admin in order to avoid any future issues.

Please let me know if you need any help or more clarification on any of the query.

Thanks,
Abhishek.