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

Runnig Apex Job realtime

I have a batch job


global class xyz  implements Database.Batchable<Sobject>  { 



I want to run it immidiately witiout running it as an apex job.Since,its takes some time to start execution, when I run it as an Apex job. How can I run it real-time ?


Thanks in advance!



If this is your requirement, I would move all of the code that is run within your xyz batch class into a separate, NON-Batch class, so that the code can be used both synchronously (i.e. real-time, executed immediately) and asynchronously (i.e. non-real-time, executed through Batch Apex).


As an extremely basic example, suppose your class xyz deletes all of the Cases that have a Status of 'Closed'.  The actual meat of xyz, which performs the deletion logic, would ordinarily be contained in the global void execute(Database.BatchableContext BC, List<Case> scope) method, which applies the deletion logic to all Cases handed to it by the Database.QueryLocator logic defined in your start method. 


All that you have to do to make this Case deletion logic (or whatever other logic takes place in your actual XYZ class) runnable from a non-Batch context is to extract it into another method, which is then called by the required Database.Batchable Interface's execute() method: 


global class xyz implements Database.Batchable<Case> {
   // Find all Cases with a Status of 'Closed'
   global Database.QueryLocator start(Database.BatchableContext BC) {
      String query = 'select id from Case where Status = 'Closed';
      return Database.getQueryLocator(query);

   global void execute(Database.BatchableContext BC, List<Case> scope){
   // (This method is separated out so as to be callable 
   // from non-Batch Apex (i.e. Unit Tests, Anonymous Apex, etc.)
   public void execute(List<Case> scope) {
       // Delete all Cases in scope

   global void finish(Database.BatchableContext BC) {



 You can then call this method from any other place in Apex that you'd like, passing in an arbitrary list of Cases, like so:


// Include this in Anonymous Apex or a Trigger
List<Case> cases = [select id from Case where Status = 'Closed' limit 100];

// Obtain a reference to the xyz class
xyz batchClass = new xyz();

// Call the execute method manually
// on the cases you just queried for

// Done!



Hope this helps!




Zach McElrath

Certified Admin, Developer

Skoodat LLC