-1

we would like to run an Apex Code when the user changes the campaign status field to Completed. What is the best way to do that without stressing the system?

I saw it is possible to do it with triggers but I do not want it to run anytime the campaign is updated.

1 Answer 1

0

That's literally what triggers are designed for. A trigger that runs but "does nothing" will run in literal milliseconds. Hardly any stress at all. Your code would look like this:

Campaign[] completedCampaigns = new Campaign[0];
for(Integer index = 0; index < Trigger.size; index++) {
  if(Trigger.old[index].Status != Trigger.new[index].Status && Trigger.new[index].Status == 'Completed') {
    completedCampaigns.add(Trigger.new[index]);
  }
}
if(completedCampaigns.size() > 0) {
  YourApexClass.doSomething(completedCampaigns);
}

(Of course, it'd be better as a trigger framework, this is only illustrative).

This code will run in sub-millisecond time if there's only one campaign being updated and it doesn't match the criteria, or about 10-20 ms for 200 records in the list (based on some tests I wrote up to try it out). That's not even 1/10th of one second.

You could also use a Flow with an Apex Action, but realistically, that's overkill for what you're trying to do.

2
  • Hi sfdcfox, Thanks for your answer. This is exactly what I was looking for. We are not only trying to run an Apex codee but also perform some outgoing API Request to an external API. Is there a Time Limit within using triggers that we need to take into concern?
    – Marc Bl.
    Commented Feb 20, 2023 at 6:41
  • @MarcBl. You can't make callouts in a trigger context. This limitation is in place to both prevent excessive resource contention and to ensure that roll backs won't affect external systems. You'll end up using a future/queueable method to perform the callouts after the trigger runs to completion.
    – sfdcfox
    Commented Feb 20, 2023 at 14:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .