I have a use case to run sequence of Batch to execute my logic. There I need to have a way to start the Batch and terminate it, So for that I keep a global variable to store the records and according to the record I was start the Batch in sequence. I will share my code below and if you have any idea please share with me to overcome this issue,
I am thinking that when we start the sequence batch their might be the global variable reset.
global class Main_BATCH implements Database.Batchable<SObject>, Database.Stateful {
global String query;
public static List<Object_Rule__mdt> ObjectAndFieldsRule;
global Main_BATCH() {
ObjectAndFieldsRule = new List<Object_Rule__mdt>();
if (ObjectAndFieldsRule.size() == 0) {
ObjectAndFieldsRule = [
SELECT soco__Action__c, soco__Order__c, soco__SObject__c,
(SELECT soco__Action__c, soco__Field_Name__c, Object_Rule__c FROM
Field_Rules__r)
FROM Object_Rule__mdt
ORDER BY soco__Order__c
];
}
this.query = 'Construct query according to the meta data Master and Child records'
}
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(this.query);
}
global void execute(Database.BatchableContext BC, List<SObject> sobjects){
try {
batchJobId = BC.getJobId();
'Do the logic'
} catch (Exception e) {
}
}
global void finish(Database.BatchableContext bc) {
Main_BATCH anonimizationMainBATCH = new Main_BATCH();
ObjectAndFieldsRule.remove(0);
if (ObjectAndFieldsRule.size() > 0) {
Database.executeBatch(anonimizationMainBATCH, 200);
}
}
}
When I run the above Batch it act as an infinite Batch with the first meta data record.