Synchronising Apex Triggers with Workflow Time Triggers

Few days back I came across a requirement which where user needed a scheduled job, that invokes after x days of record creation and creates a clone record.

So my initial thought was Scheduled Apex job but that doesn't seem to fit for this case because of the limit on number of scheduled jobs that can be scheduled. So started thinking of another approach and solution was pretty simple

WorkFlow Time Trigger + Apex Trigger = Invoke Apex @ Future Date.

Wasn't the equation clear enough? 
Well let me explain the same in steps.

  • Define Workflow
    • Create a new workflow 
      • Specify a entry criteria that fits your requirement. In my case it needs to go inside the  workflow as soon as it is created. So I just used formula editor and entered formula as "TRUE" as Rule Criteria and Evaluation Criteria as "Created". 
    • Add Time Trigger
      • Add time trigger to the apex and provide appropriate time duration. In my case I chose 30 days from "Rule Trigger Date"(Which will be same as created date). 
    • Add a field Update to the time trigger
      • Now add a field update that will be used by Apex Trigger to execute a class. So In my case the custom object had a custom field with the name "invokeApex__c" which was by default set to "FALSE".
      • Create a field update that will set this to "TRUE"

Well now you are done with the configuration part. Lets write some code
  • Creating a APEX Trigger.
    • Sample trigger will look like
       trigger invokeApexCloning on Demo__c (after update__c) {  
         for(Demo__c demo : trigger.New){  
           if(demo.invokeApex__c != trigger.Old.get(demo.Id).invokeApex__c && demo.invokeApex__c == TRUE){  
             //invoke your action here  
             CloningUtil.clone(demo);  
           }  
         }  
       }  
      
       
    • Modified version if you want to bulkify the same
       trigger invokeApexCloning on Demo__c (after update__c) {  
         List<Demo__c> demoList = new List<Demo__c>();  
         for(Demo__c demo : trigger.New){  
           if(demo.invokeApex__c != trigger.Old.get(demo.Id).invokeApex__c && demo.invokeApex__c == TRUE){  
             demoList.add(demo);  
           }  
         }  
         //invoke bulk action from here  
         CloningUtil.clone(demoList);  
       }  
      
Well thats all we are set now. This code setup will let you clone the records after 30 days. Now you know the secret to mix Time Triggers with Apex Triggers ;)

2 comments: