You need to sign in to do that
Don't have an account?
Robert Wambold 10
How to limit how many times a trigger fires in an hour?
Hello all,
Looking for advice. I have a trigger on the EmailMessage object where I use an SOQL query to look for more than 10 related records added in the last hour. My problem is that I only want to notify the administrator once, but not every record inserted after initial notification.
I was thinking I could create a "control" record with the last notification information and this culd be checked before send additional notifications.
Thanks in advance for suggestions.
I have attached my code for review and humor.
Kind regards,
Robert
trigger CountEmailMessagesCreated1HourAgo on EmailMessage (after insert) { String NEW_RelatedToId; DateTime OneHourAgo = System.Now().addHours(-1); List<String> EmlLst = new List<String>(); String Email_Sent = 'No'; for(EmailMessage Eml : Trigger.new) { NEW_RelatedToId=Eml.RelatedToId; List<AggregateResult> EmlLst = [SELECT RelatedToId, COUNT(ID) FROM EmailMessage WHERE CreatedDate>=:OneHourAgo AND RelatedToId =:NEW_RelatedToId GROUP BY RelatedToId HAVING Count(Id) >10 ]; If (EmlLst.size() >0){ If (Email_Sent == 'No'){ List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>(); Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] sendTo = new String[]{'Admin-1@group.com'}; String[] sendToCc = new String[]{'Admin-2@group.com'}; mail.setHtmlBody('Hello, <br/> This Case Id ' +NEW_RelatedToId +' has generated more than 10 Email Messages in the last hour. <br/><br/> Thanks, <br/>Salesforce Admin'); mail.setSubject('Case EmailMessage Limit of 10 Exceeded'); mail.setToAddresses(sendTo); mail.setCcAddresses(sendToCc); mails.add(mail); Messaging.sendEmail(mails); Email_Sent = 'Yes'; return;} } } }
Maybe you can try moving the logic to apex scheduler