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
Bryn JonesBryn Jones 

Apex Scheduling Help for Updating Field on Opporutnity

We would automatacilly like to update the close date field on opportunities every day based on certain criteria in the opportunity. I understand this can be done with a Apex Schedule but would like some help in how to go about writing the code for this.

Thanks.
SarvaniSarvani
Hi Bryn,

As you are trying to update list opportunities "CloseDate" field. You need a batch class which collects what are the records to be updated.You also need a schedulable class which runs this batch class and run every day at some time.

This will be your schedulable apex class code:

Step 1. Create an apex class and paste the code
global class scheduledUpdate implements Schedulable 
{
   global void execute(SchedulableContext SC) 
   { 
      // calling your batch class which has actual records to update
      UpdateClosedate  UC = new UpdateClosedate ();
      database.executebatch(UC);

    }
}

Step 2. Create an apex class and paste the code
global class UpdateClosedate implements Database.Batchable<Opportunity>{

   global Database.QueryLocator start(Database.BatchableContext BC)

  {  // collect all the records whose closed date field you need to update based on your condition
      string query = 'select id, closedate from Opportunity where YOURCONDITION';
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<Opportunity> scope )
   {
        list<Opportunity>  OppUpdateList= new list<Opportunity>();
        for(Opportunity s : scope)
           {
              s.CloseDate = system.today; // The value with which closedate should be updated
             OppUpdateList.add(s);
            }      
          update OppUpdateList ;
     }

   global void finish(Database.BatchableContext BC){

   }

}

Once both the classes are saved. You can now schedule your schedulable class created in step 1 in the UI. 

Step 3. Goto Setup -> Apex Classes -> Click on the button Schedule Apex -> You can see your schedulable class. (Refer Image)

User-added image

Note: Your class will be on the list only if you implement the schedulable class.

Links which may help:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

Hope it helps! Please mark as best if it does.

Thanks