2

I have a batch apex class that I need to fire only after all of the thousands of records from a record import have been inserted into a custom object. I thought I should use a trigger to fire my batch apex job.

I read somewhere though that the trigger would execute once for every 200 records that were inserted which I think would fire my batch apex multiple times. This is a problem because in the finish method of my batch apex, I need to execute a different batch apex job which will operate on the results of a grouping query of the same custom object's records and must take into account all of the newly inserted records at once.

1

You can put the call to the trigger code in an IF statement so that by changing one value (in this case "AppFn.s_bIsTriggerActive"), you can turn off trigger processing to allow for things like the bulk uploading of records.

If you use this technique, be certain to do it outside of normal business hours. You don't want data entered by regular users to escape the trigger processing too.

Trigger OnCustomObjectChangeTrigger on CustomObject__c(after insert, after update, after delete, after undelete)
{
   if(AppFn.s_bIsTriggerActive)
       OnCustomObjectChange.OnCustomObjectChanged();
}
  • How will this ensure that my custom code fires only after ALL of the records have been inserted, and not during the data load? – SF1Dev Jul 25 '14 at 14:49
  • You mentioned a batch job. I thought you would be using that to start the update once the bulk update was complete. If that's not the case, you'll need another batch job to touch all the affected affected records after trigger processing has been turned back on. – Jagular Jul 25 '14 at 14:57
  • 1
    Also, you're not necessarily limited to size 200 batches. From "Using Batch Apex" - "If the start method of the batch class returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000." – Jagular Jul 25 '14 at 15:22
  • The bigger problem, perhaps, is that you can't know when the bulk load is complete. Every 200 records is its own transaction, and there's no indicator as to if more data is pending. – sfdcfox Jul 25 '14 at 15:25
  • sfdcfox: Yes, this is the challenge. The 200 record limit is imposed within the trigger. My understanding is that a trigger can process up to 200 records before creating a new scope. That being the case, how can my code know when processing is all done for the entire bulk load, then launch a batch apex job with a query locator? I'm thinking maybe it's not possible to use a trigger they way I'd like. I may be stuck scheduling apex to run and check if a batch is in the process of executing and if not, execute it. – SF1Dev Jul 25 '14 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.