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
Smurfet15Smurfet15 

i need to run a flow based on the schedule time?

Hi Guro,

Here is my exact requirement, we have a flow but we need to fire this 30 days before the contract end date.
Is this possible only in Apex classe if yes can you please send a sample classe on this.

And also i need this Apex Class to run every day, so do we need to Apex Scheduler on this?


Thanks in Advace
Sumerfet

 
@Karanraj@Karanraj
You can implment using apex batch class to send email to the user or owner of the record. Write your logic in the batch apex class to identify the record where contract end - today is 30 then send the email to the owner/user based on your business logic with the url of flow.
You can schedule the batch class to run in daily basis at particular time using Apex Scheduler.

Check this below link for more details on batch class - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm
Useful blog post - http://blog.shivanathd.com/2013/01/how-to-write-batch-class-in.html
Apex Scheduler - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
Jason HardyJason Hardy
I think you should be able to use process builder on a scheduled basis (http://salesforce.stackexchange.com/questions/65734/how-to-add-time-dependent-actions-in-lightning-process-builder).

Here is one of my utilities that I use to schedule. I have simplified it a great deal for example purposes, but you should be able to get the gist:
 
/**
 * @descirption: This is a utility class for scheduled jobs that will execute hourly.
 * Will help reduce complexity by having one area to look in for all classes that need to execute hourly.
 **/
global with sharing class UtilityHourlySchedule implements Schedulable 
{
    /**
     * @description: Executes the schedulable class
     * @param sc: This is the scheduable context variable
     **/
    global void execute(SchedulableContext sc)
    {
        contactInterviewExpiration();
    }
    
    /**
     * @description: This method will check for contcacts that must be reset based on an experiation date
     * and process the ones that need to be modified.
     */
    private static void contactInterviewExpiration()
    {
        try {
            update updateContacts2Clear(checkForContacts2Reset());
        }catch(Exception e){

        }
    }
    
    /**
     * @description: This method will check for expired records.
     * @return list<Contact>: A list of contacts that match the criteria.
     */
    public static List<Contact> checkForContacts2Reset()
    {    
        return  
        [
            select id, Candidate_Status__c, Do_not_contact_before__c
            from Contact
            where Do_not_contact_before__c <=TODAY
        ];
    }
    
    /**
     * @description: This method will take a list of contacs and update them to have a null expiration date
     * as well as a status of active.
     * @param contacts: The list of contacts that will be processed.
     * @return List<Contact>: List of modified contacts that must be adjusted.
     **/
    private static List<Contact> updateContacts2Clear(list<Contact> contacts)
    {
        List<Contact> returnList = new list<Contact>();
        
        if(!contacts.isEmpty())
        {
            for(Contact c: contacts)
            {
                c.Candidate_Status__c = 'Active';
                c.Do_not_contact_before__c = null;
                returnList.add(c);
            }
        }
        
        return returnList;
    }
}

Here is the test class (modified a bit) that would work with it (also, it's 2 years old before some of the new bells and whistles came out)
/**
 * @description: This is a test utility for the hourly scheduling utility class.
 */
@isTest
private class UtilityHourlyScheduleTest 
{
    //Declaring some of the items that can be re-used for multiple tests
    private static string yr2test = string.valueof(date.today().addYears(10).year());
    private static string CRON_EXP = '0 0 0 3 9 ? ' +yr2test;
    private static list<Account> candidateAcctList = createAndInsertAccounts(3);
    private static list<Contact> candidateList = createAndInsertContacts(1,candidateAcctList);
    
    /**
     * @description: This is a test that will make sure that the interviews reset
     */
    static testMethod void testSample() 
    {     
        //Setting up the the scheduled job to run
        system.Test.startTest();
            string jobId = scheduleTestJobUtilityHourlySchedule();
            CronTrigger ct = [select id, CronExpression, TimesTriggered, NextFireTime from CronTrigger where id = :jobId];
            //Checking to make sure that the epxpressions line up
            system.assertEquals(CRON_EXP,ct.CronExpression);
            //Verifying it hasn't run yet
            system.assertEquals(0, ct.TimesTriggered);
            //Verifying that the job will run at the indicated date and time
            system.assertEquals(yr2test+'-09-03 00:00:00', string.valueOf(ct.NextFireTime));
        system.Test.stopTest();
        
        //Making sure that all of the records were updated
        System.assert(UtilityHourlySchedule.checkForContacts2Reset().isEmpty());
    }
    
    /**
     * @description: This method will generate a system schedule for the utility hourly schedule job.
     * @return string: This is the job ID that will be used for validation purposes
     **/
    private static string scheduleTestJobUtilityHourlySchedule()
    {
        return System.Schedule('UtilityHourlySchedule_Job',CRON_EXP,new UtilityHourlySchedule());
    }
    /**
     * @description: This method will create and insert a group of accounts
     * @param num2Create: The number of accounts to create
     * @return list<Account>
     */
    private static List<Account> createAndInsertAccounts(integer num2Create)
    {
        List<Account> returnList = new list<Account>();
        
        for(integer i=0; i<num2Create; i++){
            returnList.add(createAccount('Test '+i));
        }
        insert returnList;

        return returnList;
    }

    /**
     * @description: This method will create an account based on the passed account name
     * @param acctName: The Account name
     * @return Account
     */
    public static Account createAccount(string acctName)
    {
        return new Account(
            Name = acctName
        );
    }

    /**
     * @description: This method will create a list of contacts based on the list of accounts
     * @param num2create: How many contacts per account are we creating
     * @param acctList: The account list
     * @return list<Contact> List of contacts that were created and inserted
     */
    private static list<Contact> createAndInsertContacts(integer num2create, list<Account> acctList)
    {
        list<Contact> returnList = new list<Contact>();
        Date d = Date.today().addDays(-1);
        for(Account a : acctList){
            for(integer i = 0; i<num2Create; i++){
                Contact c = createContact('Test Contact '+a.Name,a.Id);
                c.Do_Not_contact_before__c=d;
                c.Candidate_Status__c='Do Not Contact';
                returnList.add(c);
            }
        }
        insert returnList;
        return returnList;
    }

    /**
     * @description: This method will create a contact based on the information passed
     * @param lName: Last name of the contact
     * @param acctID: Account ID of the contact
     * @return Contact The contact that was created
     */
    private static Contact createContact(string lName, id acctID)
    {
        String areaCode='(123) ';
        String prefix='456-';
        String num='7890';
        return new Contact(
            LastName = lName,
            AccountID = acctID,
            MobilePhone = areaCode+prefix+num);
    }
}

Hope that helps!
Smurfet15Smurfet15
Hi Jason,

Thanks for the sample code.
Can I have the "class UtilityHourlySchedule"? My guess is this is where the setting for Schedule job.

Thanks,
Mary