Skip to content

Instantly share code, notes, and snippets.

@swapnilshrikhande
Last active May 13, 2021 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swapnilshrikhande/372cd755866357c1d2226b12103c5e24 to your computer and use it in GitHub Desktop.
Save swapnilshrikhande/372cd755866357c1d2226b12103c5e24 to your computer and use it in GitHub Desktop.
Generic Chainable Batch

Create a class which implements Action interface, And pass List of actions as below. Database.executeBatch(new ActionBatch(listOfActions,0));

interface Action {
String getQuery();
Boolean execute(List<SObject> records);
Object getResult();
void setData(Object value);
Integer getDelay();
String getJobName();
}
public class ActionBatch implements Batchable<SObject>{
List<Action> actions;
Integer index;
Boolean isSuccess;
//Object state; if state is required across multiple invocations
public ActionBatch(List<Action> theActions,Integer currentIndex){
this.actions = theActions;
index=currentIndex;
}
public database.querylocator start(Database.BatchableContext BC) {
Database.getQueryLocator(actions.get(index).getQuery())
}
public void execute(Database.BatchableContext BC, List<sObject> scope) {
isSuccess = actions.get(index).execute(scope);
//actions.get(index).setState(state); to maintain state
}
public void finish(Database.BatchableContext BC){
if( isSuccess ){
Integer nextIndex = index+1;
Object result = actions.get(index).getData();
Action nextAction = actions.get(nextIndex);
nextAction.setData(result);
System.scheduleBatch( new ActionBatch(actions, nextIndex), nextAction.getJobName() , nextAction.getDelay());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment