Apex passing parameters to Batch job during scheduling

Here it the use case:

You have 1 job that you want to run weekly and monthly but the monthly job also has to generate a notification. You don’t need to create two classes but can pass a parameter to the schedule to know it is a weekly or monthly job.

The batch Job class that accepts constructor parameter jobRunFrequency
global class AccountBatchJob implements System.Schedulable, Database.Batchable<SObject>, Database.Stateful, Database.AllowsCallouts {

	private static final String RUN_WEEKLY_JOB = 'RUN_WEEKLY_JOB';
	//This is the key that needs to be used to generate notifications for Monthly 
	private static final String RUN_MONTHLY_JOB = 'RUN_MONTHLY_JOB';
	private String jobRunFrequency;

	String query = 'Select Id, FirstName, LastName from Account';

	public App_Job_Wellness_Scoring(){
		this.jobRunFrequency = RUN_WEEKLY_JOB;
	}

	public App_Job_Wellness_Scoring(String jobRunFrequency){
		this.jobRunFrequency = jobRunFrequency;
	}

        global Database.QueryLocator start(Database.BatchableContext BC) {
		return Database.getQueryLocator(query);
	}

    global void execute(Database.BatchableContext BC, List<Account> accounts) {
     ....
     if (RUN_MONTHLY_JOB.equalsIgnoreCase(jobRunFrequency)){
     ......
     }
    }
}

Test class for batch Job passing parameter check if it is the Monthly job

Test.startTest();
	Database.executeBatch(new AccountBatchJob('RUN_MONTHLY_JOB'), 1);
Test.stopTest();

Test class Scheduler Job to check it if is the Monthly job

Test.startTest();
	String jobId = System.schedule('AccountBatchJob', '0 0 0 15 3 ? 2022', new AccountBatchJob('RUN_MONTHLY_JOB'));
	CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
	System.assertEquals('0 0 0 15 3 ? 2022', ct.CronExpression);
Test.stopTest();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: