You need to sign in to do that
Don't have an account?
How to force order of events in Batch Apex
Hello!
I have a batch apex that is running through 5 CSV attachments, and creating records from the data that is in the files.
Each CSV file is for a different object, and sometimes there are lookup relationships between them (like Account < Contact).
How can I make sure that the CSV files are read & processed in the correct order?
I want the Accounts to be created first, and then the Contacts follow (because the Contacts are related to Accounts) and the rest of the CSV files should follow.
I tried putting the files in order, but this is not working out...
Here are some code examples:
global String getDocumentQuery() { return 'SELECT Id, Name, Body FROM Attachment WHERE ParentId =: JobId order by Name asc'; }
global void execute(Database.BatchableContext context, List<SObject> records) { //get Accounts Attachment accountsAttachment = getAttachmentByType('accounts', records); if (accountsAttachment != null) { List<List<String>> accountsCsvRecords = parseCSV.parseCSV(accountsAttachment.Body.toString(), true); import (accountsCsvRecords, 'Account'); } //get Contacts Attachment contactsAttachment = getAttachmentByType('contacts', records); if (contactsAttachment != null) { List<List<String>> contactsCsvRecords = parseCSV.parseCSV(contactsAttachment.Body.toString(), true); import (contactsCsvRecords, 'Contact'); } }
You can see that my execute function gets a list of SObjects (which are the Attachments themselves), but the batchable nature of the class makes it asynchronous, and the import will finish at random times on each Attachment.
Any way to make this synchronous, and still be able to run thru a big list of objects without any SOQL error?
Let's say you have 3 csv attachments processed to be in this order : Account, Contact, Opportunity.
Create 3batches:
OpportunityBatch {
start(){
//fetch only Opportunity csv attachment
}
execute (){
//query accounts and contacts created/modified yesterday/today [recently imported filter ]
// process opportunity csv, import it ,link it with lookups
}
finish (){
}
}
ContactBatch {
AccountBatch {
If you execute only AccountBatch it works synchronously calling contact batch once it finishes it's execution. Then, contact batch starts, after its execution opportunity batch starts.