I have a scheduled batch class which runs repeatedly over some groups of accounts. In the finish-method I start the next batch if some condition is true. Simplified code:
global void finish(Database.BatchableContext BC) {
if (condition) {
// start next batch
Database.executeBatch(new MyBatch(), 1);
}
}
Now I want to gather some logging messages in the execute method. When the last batch is ready, I want to send a mail with all messages. I wrote a simple logging class which will be passed to the batch:
global class MyLog {
// Map Account ID to message
private Map<String, String> messages;
global MyLog() {
this.messages = new Map<String, String>();
}
public void add(Account myAccount, String message) {
this.messages.put(myAccount.Id, message);
}
public String getMessages() {
String result = '';
for (String txt: this.messages.values()) {
result = result + txt;
}
return result;
}
}
MyLog Object will be created once in MyBatch constructor (first batch is called with null):
global class MyBatch {
MyLog log;
global MyBatch(MyLog log) {
// first batch gets null from scheduler
// log object is passed to all others
this.log = (log == null) ? new MyLog() : log;
}
global void execute(Database.BatchableContext bc, list<Account> myAccounts) {
this.log.add(account, 'some log message');
}
global void finish(Database.BatchableContext BC) {
if (condition) {
// start next batch
Database.executeBatch(new MyBatch(this.log), 1);
}
else sendLogsAsMail();
}
}
This doesn't work. After last batch is executed correctly, MyLogs.messages is always empty. If I write system.debug in execute method, I see that messages contains one key/value pair for the processed account. But it seems that the passed log object doesn't change. Can anyone see what is wrong with my code? Or is there any other approach to pass data between batches?
Best Regards