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 AccountBatchJob(){ this.jobRunFrequency = RUN_WEEKLY_JOB; } public AccountBatchJob(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();