[SalesForce] How to i call a schedule class execute method from normal apex class or apex trigger

How can i call a schedule class execute method from normal apex class or apex trigger. I also need to pass some variables like(daily,weekly,monthly) based on which i like to schedule the class like weekly or monthly or daily. Is it possible?

Best Answer

I think you can use something like following:

global class Dummy_Schedulable_Class implements Schedulable{

    global String dailyCronExpression = '0 0 13 * * ?';
    global String monthlyCronExpression = '0 0 13 1 * ?';
    global String weeklyCronExpression = '0 0 13 ? * 1';

    global void execute(SchedulableContext SC) {

    }

    public static void scheduleThis(String argPass){
        String cronExp;
        if ( 'daily'.equals( argPass ) ) {
            cronExp = dailyCronExpression;
        } else if ( 'monthly'.equals( argPass ) ) {
            cronExp = monthlyCronExpression;
        } else if ( 'weekly'.equals( argPass ) ) {
            cronExp = weeklyCronExpression;
        }
        System.assertNotEquals(null, cronExp, 'Please pass "daily" "monthly" or "weekly" argument to this method.');
        System.schedule('test', cronExp, new Dummy_Schedulable_Class());
    }

}

and then call

Dummy_Schedulable_Class.scheduleThis('monthly');

or

Dummy_Schedulable_Class.scheduleThis('daily');

or

Dummy_Schedulable_Class.scheduleThis('weekly');

String constant dailyCronExpression = '0 0 13 * * ?' means 'every day at 1 p.m.' String constant dailyCronExpression = '0 0 13 1 * ?' means 'every first day of month at 1 p.m.' String constant dailyCronExpression = '0 0 13 * * ?' means 'every first day of week at 1 p.m.'

Please mark this answer as accepted if you agree it accurately and precisely answers your question, please vote up this answer if you find it useful.