Schedulable service method launcher
The main goal is to let the scheduler register and manage its own schedule. It keeps the CRON expression and job name in one place, calls a service method when it runs, and adds a dedicated suffix to test job names.
/**
* Replace YourService.doJob() with the service method your job should run.
*/
public with sharing class ScheduledServiceJob implements Schedulable {
@TestVisible private static final String CRON_EXPRESSION = '0 0 * * * ?';
@TestVisible private static final String JOB_NAME = 'Scheduled Service Job';
public void execute(SchedulableContext context) {
YourService.doJob();
}
public static String scheduleMe() {
return System.schedule(
JOB_NAME + (Test.isRunningTest() ? ' - TEST' : ''),
CRON_EXPRESSION,
new ScheduledServiceJob()
);
}
}
@IsTest
private class ScheduledServiceJobTest {
@IsTest
static void scheduleMe_usesTestJobName_andReturnsJobId() {
Test.startTest();
String jobId = ScheduledServiceJob.scheduleMe();
CronTrigger scheduledJob = [
SELECT CronJobDetail.Name
FROM CronTrigger
WHERE Id = :jobId
];
Test.stopTest();
Assert.isNotNull(jobId);
Assert.areEqual(
ScheduledServiceJob.JOB_NAME + ' - TEST',
scheduledJob.CronJobDetail.Name,
'Tests must use the dedicated test job name.'
);
}
}