I have my simple trigger working now where once a threshold is met for cases created within 60 minutes it updates the "SendAlert" field so my workflow can start going to work.

The next steps I am trying to figure out is if it is possible to only have this occur during non-business hours?

trigger OutageAlert on Case (before insert) {
date today =system.today();
List<Case> numberofcases = [SELECT ID FROM CASE where SLA__c<=:1];
    for(case cas:trigger.new){
        if(cas.origin == 'Web - Email'){
            if(numberofcases.size() == 5) {
                cas.SendAlert__c = true;
            if(numberofcases.size() == 10) {
                cas.SendAlert__c = true;

How can I add a function into this where it will only run during non-business hours?

Clarification: I want the field SendAlert__c to not go active while in business hours, is this possible in a workflow maybe since its not possible in the trigger?

  • Welcome to SFSE Craig! Triggers only run when a DML event occurs so am I understanding that if some Case is created outside of business hours, then you want the SendAlert__c field to stay false? And not until some other case is inserted during business hours that you want the flag set on the 'other' case? So cases created after business hours NEVER have the SendAlert field set?. Please use edit to clarify
    – cropredy
    Commented Jul 12, 2019 at 1:32
  • Thanks for the welcome :) I edited my post to clarify and maybe it is something that needs to be a workflow or process builder instead if the trigger cannot use time or the business hours within Salesforce? Commented Jul 12, 2019 at 13:53
  • 1
    Are you using the Business Hours feature? that is, are business hours and holidays defined in the OOTB metadata?
    – cropredy
    Commented Jul 12, 2019 at 14:11

1 Answer 1


If you've defined your business hours in metadata, you should be able to use the isWithin function to determine if the current datetime (DateTime.Now()) is within those defined business hours.

From the documentation:

public static Boolean BusinessHours.isWithin(String businessHoursId, Datetime targetDate) 

Returns true if the specified target date occurs within business hours. Holidays are included in the calculation.

BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];

if (BusinessHours.isWithin(bh.Id, DateTime.now())) {
  // Handle
} else {
  // Handle another way
  • Hi Battery,cord I think you got me where I need to go. for the first //handle (the IF) can I just put Return; then under the }else{ I put my code as above? will that then let the case be created if it is within Business hours but if not it will follow the code above? Commented Jul 12, 2019 at 15:22

You must log in to answer this question.

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