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
Sai Bhaskar 16Sai Bhaskar 16 

Hi everyone I have got a scenario where I need to write a batch Apex to close all the pending opportunities of previous month, batch should schedule on every hour by using schedulable interface

Hi Everyone 
 
 I have got a scenario where I need to write a batch Apex to close all the pending opportunities of the previous month, the batch should schedule on every hour by using schedulable interface
Khan AnasKhan Anas (Salesforce Developers) 
Hi Sai,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Batch Apex:
global class Batch_UpdateOpportunity implements Database.Batchable<sObject>{
    
    global Database.querylocator start(Database.BatchableContext BC){
        String query = 'SELECT Id,Name,StageName,CreatedDate FROM Opportunity WHERE CreatedDate = Last_N_Months:1';
        System.debug('query -> ' + query);
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Opportunity> scope1){
        System.debug('scope1 -> ' + scope1);
        List<Opportunity> oppList = new List<Opportunity>();
        for(Opportunity opp : Scope1){ 
            if(opp.StageName != 'Closed Won' || opp.StageName != 'Closed Lost'){
                opp.StageName = 'Closed Lost';
                oppList.add(opp);
            }
        }       
        System.debug('oppList -> ' + oppList);
        update oppList; 
    }
    
    global void finish(Database.BatchableContext BC){
    }
}

Now, We have the batch class ready and it has to be in a schedulable context in-order to schedule the batch

Scheduled Apex:
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
          Batch_UpdateOpportunity b = new Batch_UpdateOpportunity(); 
          
          //Parameters of ExecuteBatch(context,BatchSize)
          database.executebatch(b,100);
     }
}

Finally, schedule the batch class by executing anonymous code from either developer console or apex, the minimum is 1 hour:

// Cron EXP for hourly schedule: 
String CRON_EXP = '0 0 * * * ?'; 
SheduledBatchable sch = new scheduledBatchable(); system.schedule('Hourly Example Batch Schedule job', CRON_EXP, sch);

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas