How to write a Schedulable Apex Batch Class

Introduction

In this article, we will learn how to schedule an apex Batch Class in Salesforce without creating multiple classes.

Apex Code

global class ScheduledApexBatch implements Database.Batchable<sObject>, Schedulable {

  private String query;
  
  global ScheduledApexBatch (String queryString){
    query = queryString;
  }
  
  // The batch job starts
  global Database.Querylocator start(Database.BatchableContext bc){
    //String query = 'SELECT Id, FirstName FROM Lead';//In case of customized query
    return Database.getQuerylocator(query);
  } 
  
  // The batch job executes and operates on one batch of records
  global void execute(Database.BatchableContext bc, List<sObject> scope){
    System.debug('>>>> execute ' + scope.size());
    //perform business logic
  }
  
  // The batch job finishes
  global void finish(Database.BatchableContext bc){
    AsyncApexJob job = [SELECT Id, Status FROM AsyncApexJob WHERE Id = :bc.getJobId()]; 
    System.debug('>>>> finish ' + job.Status);
  }

  public void execute(SchedulableContext context){
      // Implement the scheduling logic here
      ScheduledApexBatch batchJob = new ScheduledApexBatch();
      Database.executeBatch(batchJob, 200); 
  }
}