[SalesForce] How to make the trigger only fire after all (of several thousand) records are finished being inserted

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.

Best Answer

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();
}