Time-Based Workflow Rules

Video Overview

Watch the video above for a look at a real-life scenario where time-based workflow rules can be utilized.

Note: I’ve been using Process builder often recently. Although it’s not without some drawbacks, it provides some of the functionality here as well. It provides time-based options for scheduling events and transactions on the platform, but not necessarily with business hours. It’s also extensible via Invocable Apex classes. Check out this post for an intro!

Code to the very simple trigger used is as follows:

trigger SetPromptContactTime on Lead (before insert) {
    BusinessHours bh = [SELECT Id FROM BusinessHours WHERE Name = 'My Business Hours'];
    for (Lead newLead: Trigger.new) {
        Datetime nowDate = Datetime.now();
        Long interval = 24*60*60*1000;
        Datetime expireDate = BusinessHours.add(bh.Id, nowDate, interval);
        newLead.Prompt_Contact_By__c = expireDate;
    }
}

We must use a trigger to set this date because workflow rules don’t honor business hours settings, unfortunately. If business hours aren’t particularly necessary for your use case, consider skipping the creation of a custom field and using a standard one like CreatedDate instead.

Additionally, the shortest interval you can use is 1 hour. However, there’s still a workaround if you need a shorter interval. If you want a workflow rule to run 5 minutes after the creation of a record, for example, you can follow the process but set the datetime for -55 minutes (55 minutes prior to the CreatedDate), and create a rule to run 1 hour after that datetime. As always, scheduling can be a bit finnicky, so make sure you test your creations or design solutions that aren’t extremely time-sensitive.

Lastly, recall that Prompt_Contact_By__c is a custom field of type Datetime that we created, and My Business Hours is the name of the business hours object we created. You could also query business hours by Id, and instead of using Datetime.now(), you could use the CreatedDate by changing the trigger to execute after insert.

Add comment

Recent Posts

Categories