Skip to content

Instantly share code, notes, and snippets.

@nithesh1992
Last active June 27, 2020 01:32
Show Gist options
  • Save nithesh1992/94b4195347f687c3d1cc82967c603fec to your computer and use it in GitHub Desktop.
Save nithesh1992/94b4195347f687c3d1cc82967c603fec to your computer and use it in GitHub Desktop.
Scheduled APEX - dynamic run time batch instance (Intriguing Design Pattern)
global class ApexScheduler implements Schedulable {
String className;
global ApexScheduler(String className){
this.className = className;
}
public Interface IScheduler {
void execute(SchedulableContext sc);
}
global void execute(SchedulableContext sc) {
Type classToSchedule = Type.forName(className);
if(classToSchedule !=null) {
IScheduler schedulerCls = (IScheduler) classToSchedule.NewInstance();
schedulerCls.execute(sc);
}
}
}
global class SampleBatch implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator('SELECT Id, ContactId FROM Case WHERE CreatedDate=TODAY');
}
global void execute(Database.BatchableContext BC, List<Case> scope){
for(Case caseRec : scope){
caseRec.Subject = 'X'+System.now();
}
update scope;
}
global void finish(Database.BatchableContext BC){
}
}
global class SampleBatchScheduler implements ApexScheduler.IScheduler {
global void execute(SchedulableContext sc) {
Database.executeBatch(new SampleBatch());
}
}
System.schedule('Case Update Job ', <cron exp>, new ApexScheduler('SampleBatchScheduler));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment