function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ankit Kalsara 6Ankit Kalsara 6 

How to perform time dependent workflow actions using apex trigger

Hi team,

I have workflow rule which sends email notification once the criteria is met and sends another notification 30days after the rule trigger date.

I am replacing the entire workflow rule using apex trigger. How do I send email notification 30days after the initial rule trigger date?
AnudeepAnudeep (Salesforce Developers) 
Hi Ankit, 

You should Messaging.SingleEmailMessage to send a custom notification in your trigger. Below is a sample code
 
public class TrainingExpiring30Days {
    @InvocableMethod
    public static void sendEmail(List<Certification__c> certif) {
    String sourceAccountId = String.valueOf(certif[0].Id);
    List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();
 Certification__c cert = [select id,Account__c from Certification__c Where id = :sourceAccountId];


    List<Contact> contactsToEmail = [SELECT Id
                                     FROM   Contact
                                     WHERE  AccountId = :cert.Account__c AND CPP_Access__c INCLUDES ('Receive Training Expiry Notices')];


    Id templateId = [SELECT Id 
                     FROM   EmailTemplate 
                     WHERE  Name = 'CPP: Training expiring 30 days'].Id;

    string SenderName = UserInfo.getUserName();        

    system.debug('Sender Name is:'+ SenderName);        

    for(Contact con: contactsToEmail ){

      Messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
      email.setTemplateId(templateId);
      email.setTargetObjectId(con.Id);
      email.setSenderDisplayName(Es); 
      mail.setWhatId(cert.id);
      emailsToSend.add(email);

    }
    Messaging.sendEmail(emailsToSend);  
}

If you want to Generate critical date reminders to remind Opportunity owners for example when a large Opportunity (amount greater than $1M USD) is 14 days away from the intended Close Date, you should perform a query on opportunity instead with the filters that would match your rule

Let me know if this helps

Anudeep
Ankit Kalsara 6Ankit Kalsara 6
Hi Anudeep,

This code just sends the email notification which I have already implemented. My requirement is once the email is sent, I need to resend the email after 30days (certain number of days).

I want to replicate the functionality available in workflow time trigger actions.