[SalesForce] Getting Scheduled Apex Job name in the apex class

I have two scheduled apex jobs ScheduleJob1 and ScheduleJob2. Both these jobs call an apex class implementing the Schedulable interface

global class TaskController implements Schedulable {

     global void execute(SchedulableContext sc) {
            // code
     }
}

Now ScheduleJob1 is schedule to run every monday, whereas ScheduleJob2 is schedule to run first friday of every month.

In the execute method of TaskController depending upon which scheduled job called it, I want to perform separate code logic.

So something like this

global void execute(SchedulableContext sc) {

     if(ScheduleJob1 called this class) {
          //code logic 1
     } else if (ScheduleJob2 called this class) {
         //code logic 2
     }
}

I know we can get the ID of the CronTrigger scheduled job using getTriggerId() of the SchedulableContext interface. But how do I associate that Id with the Name of the job.

Can I do something like this:

global void execute(SchedulableContext sc) {
     List<CronTrigger> cronTriggerList = [select CronJobDetail.Name from CronTrigger where CronJobDetail.Id = :sc.getTriggerId()];

     if(cronTriggerList[0].CronJobDetail.Name == 'ScheduleJob1') {
          //code logic 1
     } else if (cronTriggerList[0].CronJobDetail.Name == 'ScheduleJob2') {
         //code logic 2
     }
}

Best Answer

I would suggest adding it as an input variable:

global class TaskController implements Schedulable {

    String thisInput;

    global TaskController(String input) {
        thisInput = input;
    }

    global void execute(SchedulableContext sc) {
        if(thisInput == 'ScheduleJob1') {
            //code logic 1
        } else if (thisInput == 'ScheduleJob2') {
            //code logic 2
        }
    }

}

... then you'd schedule it like:

System.schedule('ScheduleJob1_20140818', '0 0 1 ? * 2', new TaskController('ScheduleJob1'));