I have configured finish method to send error files on csv upload. It works ok for 200 records but if the sheet exceeds records more than 200 say 2000 I am getting emails for every job that has finished.
So after the job is finished I have 5 error files in my mailbox. Is there a any way to handle this.
global void finish(Database.BatchableContext BC)
{
if(!errormap.isempty())
{
asyncapexjob a = [select Status,id ,apexclassid,jobitemsprocessed,totaljobitems,numberoferrors,createdby.email from asyncapexjob where id=:BC.getJobId()];
if(a.Status=='Completed')
{
string body = 'Dear User \n'
+'Your bulk upload of Sites'
+'has finished. \n'
+'There were '
+errormap.size()
+' errors. Please find the error list attached .';
string finalstr ='sno,Name,red,error \n';
string subject ='error file subject';
string attname = 'errorfile.csv';
for(decimal id:errormap.keyset())
{
string err = errormap.get(id);
object1__c s = (object1__c)idtosobjectmap.get(id);
string recng = '"'+s.sno__c+'","'+s.Name+'","'+s.red__c+'","'+err+'"\n';
str = str+recng;
}
messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
messaging.EmailFileAttachment efa = new messaging.EmailFileAttachment();
efa.setFileName(attname);
efa.setBody(blob.valueOf(str));
email.setSubject(subject);
email.setToAddresses(new string[] {a.createdby.email});
email.setPlainTextBody(body);
email.setFileAttachments(new messaging.EmailFileAttachment[] {efa});
messaging.SendEmailResult [] r = messaging.sendEmail(new messaging.SingleEmailMessage[] {email});
}
}
}
````
List<Database.SaveResult> srs = Database.insert(list1, false); integer Index = 0; for (Database.SaveResult sr : srs) { if (!sr.isSuccess()) { String errmsg = sr.geterrors()[0].getmessage(); errormap.put(list1[index].Row__c,errmsg); idtosobjectmap.put(list1[index].Row__c,list1[index]); } index++; } }
I am already logging the errors. The problem here is the finish method is firing for every batch. For 400 records - 2 emails are triggered