Assuming the number of deletes is not massive, the Database.Stateful
approach is a good one. Store in a property the information from the execute
method you want to email and email that information in the finish
method using the SingleEmailMessage classes.
I suggest these changes:
- unless you are creating a managed package, use
public
not global
- in the
start
method, use static SOQL not dynamic SOQL (Google to discover the difference)
- in the
execute
method, delete the whole list in one DML statement rather than one at a time
- see the DeleteResult class for how to find out what the results are
- add code to the finish method to send the email; Google about Visualforce Email Templates for how to use those
- write a unit test
I would start out doing all this inline (not in a helper class) and see how clean the result is. If your company has a policy to always move code out of triggers, then you can do that as a second step. But in this case, the overall result is likely to be worse if you do that than leaving the code inline.
PS
Hang on, isn't "move code out of triggers" a "best practice"? Well yes that is often said, but in reality, that approach is a solution to a set of problems, and if those problems don't exist, or attempting to solve those problems creates worse problems, then it is not always the right thing to do. Be wary of that label - see e.g. There is no such thing as "Best Practices": Context Matters.
Another example of a good idea getting treated as something you should always do is mentioned in Martin Fowler's new edition of his excellent Refactoring book. On the Law of Demeter his view is:
I'd prefer it to be called the Occasionally Useful Suggestion of
Demeter.
PPS
How to use a helper class. Note the static
on the helper method.
public class ITSDeleteIntegrationJobRecords implements Database.Batchable<sobject>,Database.Stateful {
private String[] emailAddresses;
private String[] results = new String[] {};
public ITSDeleteIntegrationJobRecords(String[] emailAddresses) {
this.emailAddresses = emailAddresses;
}
public Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([
select Id, name, createddate
from Integration_Job__c
where createddate < LAST_N_DAYS:60
]);
}
public void execute(Database.BatchableContext bc, List<Integration_Job__c> scope) {
results.addAll(MyHelper.execute(scope));
}
public void finish(Database.BatchableContext bc) {
String s = 'Results are\n\n' + String.join(results, '\n');
// Send to emailAddresses using a template
}
}
public class MyHelper {
public static String[] execute(List<Integration_Job__c> scope) {
// Delete and extract results
}
}