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
Manish Verma 4Manish Verma 4 

Batch apex

Hello friends, 
My requirement is: for all the Contacts, update status equal active in batch apex. Schedule this to run at 9 pm daily.
need help.

Thank you
KaranrajKaranraj
Hi Manish - You have to write one batch to excute the logic and one schedulable apex class to run the batch job at regular interval of time. Try the below code, make to sure to update the code with the  API name of the status field in your org 

Batch Apex class
This below batch class will get the all the contact records where the status is not equal active and then in the execute method, it will update the status field into Active.
global class updateContactRecord implements Database.Batchable<Contact>{

      // Start Method
      global Database.QueryLocator start(Database.BatchableContext BC){
         return Database.getQueryLocator('Select id,status__c from contact where status__c != \'Active\'');
        }    
      // Execute Logic
       global void execute(Database.BatchableContext BC, List<Contact>scope){
              for(contact con : scope){
                 con.status__c = 'Active';
               }    
            update scope;
       }
      
      global void finish(Database.BatchableContext BC){
            // Logic to be Executed at finish
       }
    }
Schedulable Apex class
Then create Schedulable apex class to run the batch class in the scheduled interval of time. This class will call the above batch class to update the contact record
global class scheduledBatchable implements Schedulable{ 
   global void execute(SchedulableContext sc) {
      // Implement any logic to be scheduled
     // We now call the batch class to be scheduled 
     updateContactRecord b = new updateContactRecord(); 
     //Parameters of ExecuteBatch(context,BatchSize) 
     database.executebatch(b,10); 
} 
}
Then you can schedule this class to run daily at 9pm. Follow the below steps
  • Goto > Setup> Develop>Apex classes
  • Click Schedule Apex button
  • Then specify the job name and select the schedulable class
  • Then set the date, day and time to run.

To know more details about batch class check this link - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch.htm

Thanks,
Karanraj (http://www.karanrajs.com)
 
Manish Verma 4Manish Verma 4
Hi Karanraj,
Thanks for considering my requirement.
But i am getting an error in batch apex class : 
Error: Compile Error: updateContactRecord: Class must implement the global interface method: Iterable<Contact> start(Database.BatchableContext) from Database.Batchable<Contact> at line 1 column 14

how can i resolve this?