I have implemented a recursive batch job in 2 different time intervals based on the below conditions:
1. If the first execution doesn't contain any errors then execute the same batch job in the next 30 seconds.
2. If there are any errors in the first execution then execute the same batch job after 1 minute.
Batch Job Code snippet :
To Initiate the batch Job, for the first time, run the below code snippet from Execute anonymous window
tHiNk gooD and dO thE bEsT.........MANJU NATH 🌝
1. If the first execution doesn't contain any errors then execute the same batch job in the next 30 seconds.
2. If there are any errors in the first execution then execute the same batch job after 1 minute.
Batch Job Code snippet :
global class MyBatchCls implements Database.Batchable<sObject>,Schedulable { global Database.QueryLocator start(Database.BatchableContext BC) { return Database.getQueryLocator([SELECT Id,Name from Account]); } global void execute(Database.BatchableContext bc, List<Account> scope) { for(Account acc: scope) { acc.Name = 'My batch'+acc.Name; } update scope; } global void finish(Database.BatchableContext bc) { AsyncApexJob asyncJob = [SELECT ID,Status,NumberOfErrors FROM AsyncApexJob WHERE ID =:bc.getJobId()]; if(asyncJob.NumberOfErrors== 0) { // Schedule again for 30-seconds Datetime sysTime = DateTime.now(); sysTime = sysTime.addSeconds(30); String log_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year(); System.schedule('MY NEW Batch Name no error',log_exp,new MyBatchCls()); } else { system.debug('I found errore so delaying for 30 more seconds'); // Schedule again for 60-seconds Datetime sysTime = DateTime.now(); sysTime = sysTime.addSeconds(60); String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year(); String log_exp = sysTime.hour() + ':' + sysTime.minute() + ':' + sysTime.second(); System.schedule('MY NEW Batch Name with Errors'+log_exp,chron_exp,new MyBatchCls()); } } public void execute(SchedulableContext sc) { Database.executeBatch(new MyBatchCls(), 200); } }
To Initiate the batch Job, for the first time, run the below code snippet from Execute anonymous window
System.scheduleBatch(new MyBatchCls(), 'MyBatchCls', 1);
tHiNk gooD and dO thE bEsT.........MANJU NATH 🌝
Comments
Post a Comment