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
Vianney Bancillon 8Vianney Bancillon 8 

Implement Schedulable interface and Database.Batchable interface in a single class

Hi everyone!

I read in a previous post that it is possible to implement both in a single class, but the post didn't give any exemples.
Could you explain  how to do that to me (with exemples if possible)
Thanks!
Vianney Bancillon
Best Answer chosen by Vianney Bancillon 8
Saurabh BSaurabh B
Hi Vianney, please see working example below... Look at the first line.. .you can add word "Schedulable" after adding a comma after Database.Batchable<sObject> ... Additionally, look at the last 3 lines, it  allow you to execute SchedulableContext ...
 
global class UpdateRateCardBatch implements Database.Batchable<sObject>, Schedulable {


        global Database.QueryLocator start(Database.BatchableContext BC){
            string myX = 'x';
String query = 'SELECT Advert_Assignment__c,borrado__c,Id,Product_Node__c FROM rate_card_item_price__c WHERE borrado__c != :myX' ;
         return Database.getQueryLocator(query);
        }
      

       global void execute(Database.BatchableContext BC, List<rate_card_item_price__c>scope){

                Map <id,String> RateMaps  = New Map <id,String> ();  
           Set <id> prodIds = New Set <id> ();
           
           List <Advert_Assignment__c> AAList = New List <Advert_Assignment__c> ();
               List <Product_Node__c> PList = New List <Product_Node__c> ();
    
           For (rate_card_item_price__c RC: scope) {
               if (Rc.borrado__c != 'x')
               RateMaps.put(rc.Advert_Assignment__c,rc.Product_Node__c) ;
               prodIds.add(RC.Product_Node__c);
               system.debug(ratemaps);
                    }
                   
           List <Advert_Assignment__c> advAsgn = [SELECT ID,Title_Product_Node__c FROM Advert_Assignment__c WHERE ID IN :RateMaps.keySet() ];        
                                  system.debug(advAsgn);

           For (Advert_Assignment__c AA : advAsgn) {

               if (AA.Title_Product_Node__c == null)
             system.debug(String.valueOf(RateMaps.get(AA.id)));
            AA.Title_Product_Node__c = String.valueOf(RateMaps.get(AA.id)) ;                   
            AAList.add(AA);
           }
           
           List <Product_Node__c> ProdList = [SELECT ID,Media_Types__c FROM Product_Node__c WHERE ID IN:prodIds ];
           
           For (Product_Node__c P :ProdList ){
               P.Media_Types__c = 'Print';
               PList.add(P);
               
           }
           
             Update AAList;  
             Update Plist;
           }
      
       global void finish(Database.BatchableContext BC){

       }
    
     global void execute(SchedulableContext sc) {
         UpdateRateCardBatch b = new UpdateRateCardBatch ();
         database.executebatch(b);
     }
    
     }

 

All Answers

Saurabh BSaurabh B
Hi Vianney, please see working example below... Look at the first line.. .you can add word "Schedulable" after adding a comma after Database.Batchable<sObject> ... Additionally, look at the last 3 lines, it  allow you to execute SchedulableContext ...
 
global class UpdateRateCardBatch implements Database.Batchable<sObject>, Schedulable {


        global Database.QueryLocator start(Database.BatchableContext BC){
            string myX = 'x';
String query = 'SELECT Advert_Assignment__c,borrado__c,Id,Product_Node__c FROM rate_card_item_price__c WHERE borrado__c != :myX' ;
         return Database.getQueryLocator(query);
        }
      

       global void execute(Database.BatchableContext BC, List<rate_card_item_price__c>scope){

                Map <id,String> RateMaps  = New Map <id,String> ();  
           Set <id> prodIds = New Set <id> ();
           
           List <Advert_Assignment__c> AAList = New List <Advert_Assignment__c> ();
               List <Product_Node__c> PList = New List <Product_Node__c> ();
    
           For (rate_card_item_price__c RC: scope) {
               if (Rc.borrado__c != 'x')
               RateMaps.put(rc.Advert_Assignment__c,rc.Product_Node__c) ;
               prodIds.add(RC.Product_Node__c);
               system.debug(ratemaps);
                    }
                   
           List <Advert_Assignment__c> advAsgn = [SELECT ID,Title_Product_Node__c FROM Advert_Assignment__c WHERE ID IN :RateMaps.keySet() ];        
                                  system.debug(advAsgn);

           For (Advert_Assignment__c AA : advAsgn) {

               if (AA.Title_Product_Node__c == null)
             system.debug(String.valueOf(RateMaps.get(AA.id)));
            AA.Title_Product_Node__c = String.valueOf(RateMaps.get(AA.id)) ;                   
            AAList.add(AA);
           }
           
           List <Product_Node__c> ProdList = [SELECT ID,Media_Types__c FROM Product_Node__c WHERE ID IN:prodIds ];
           
           For (Product_Node__c P :ProdList ){
               P.Media_Types__c = 'Print';
               PList.add(P);
               
           }
           
             Update AAList;  
             Update Plist;
           }
      
       global void finish(Database.BatchableContext BC){

       }
    
     global void execute(SchedulableContext sc) {
         UpdateRateCardBatch b = new UpdateRateCardBatch ();
         database.executebatch(b);
     }
    
     }

 
This was selected as the best answer
Vianney Bancillon 8Vianney Bancillon 8
Awesome!
Thanks Saurabh...
 
Ashwin KhedekarAshwin Khedekar
/*
Same class can implement both interface Database.Batchable and Schedulable. These two names have to be comma-separated after the "implements" keyword in the class defition. In the below code "Check_x_min_trigger__c" is a custom field of type text on Account. The batch class queries for all accounts and assigns the value "Same class implements both interfaces" to this custom field on all the account records. The "execute" method given in the end (which takes parameter SchedulableContext) is called to schedule the Apex Scheduler from Developer Console using this code :-
DoubleImplement doubleImplementObj = new DoubleImplement();
String timeScheduleString = '0 20 * * * ?'; // Apex Scheduler will run 20 minutes past every hour
String schedulerJobID = system.schedule('Scheduler Name String', timeScheduleString, doubleImplementObj);

Open the "Open Execute Anonymous Window" of Developer Console from this path (to run the above three lines of code) :-
Setup -> Developer Console -> Debug -> Open Execute Anonymous Window

See the scheduled apex job at this path :-
Setup -> Monitor -> Jobs -> Scheduled Jobs
*/

global class DoubleImplement implements Database.Batchable<SObject>, Schedulable
{
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        String query = 'Select id, name, City__c, Check_x_min_trigger__c from Account';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<SObject> scope)
    {
        System.debug(LoggingLevel.INFO, '#### execute method of batch class starts');
        List<Account> accLstToUpdate = new List<Account>();
        if(scope != null)
        {
            List<Account> accLst = (List<Account>)scope; // typecast List<SObject> to List<Account>
            for(Account a : accLst)
            {
                a.Check_x_min_trigger__c = 'Same class implements both interfaces';
                accLstToUpdate.add(a);
            }
            
            if(accLstToUpdate.size() > 0)
            {
                System.debug(LoggingLevel.INFO, '#### execute method of batch class: updating accLstToUpdate ' + accLstToUpdate.size());       
                update accLstToUpdate;
            }
        }
    }

    global void finish(Database.BatchableContext BC)
    {
        System.debug(LoggingLevel.INFO, '#### finish method of batch class');
    }

    global void execute(SchedulableContext sc)
    {
        System.debug(LoggingLevel.INFO, '#### execute method of scheduler starts');
        DoubleImplement di = new DoubleImplement();
        Database.executeBatch(di);
    }
}