[SalesForce] How to Re-Create Scheduled Jobs After Deleting Them

I need to make some changes to a schedulable class that inserts Case Share objects for our custom permissioning model. When trying to make changes to the class, the error is thrown that the class has pending jobs in progress. I am able to find the jobs under Scheduled Jobs, but they were written and scheduled years ago by consultants.

Is there a way to recreate these jobs identically after I have deleted them (in order to make changes to the class)? Since they are not editable, I cannot look in and see the components like what classes/methods are called and when it is scheduled to run.

Best Answer

If the event was scheduled via the UI, you should be able to get the information you want via SOQL. Here's the problem: CronTrigger has most of the data points you need, which you can access through CronJobDetail if you query on Name, which you can see. But the only way to determine which ApexClass is scheduled is via AsyncApexJob, which has no relationship to either SObject.

An unofficial source claims that the CreatedDate should match if the job was scheduled through the UI. So if that is the case, you should be able to get the data with two queries. The following worked for me in Execute Anonymous to infer the necessary data:

CronTrigger jobData = [
    SELECT CreatedDate, CronExpression, EndTime
    FROM CronTrigger WHERE CronJobDetail.Name = 'Job I Want To Delete'
];
AsyncApexJob execution = [
    SELECT ApexClass.Name FROM AsyncApexJob
    WHERE CreatedDate = :jobData.CreatedDate
];
system.debug(jobData.EndTime);
system.debug(jobData.CronExpression);
system.debug(execution.ApexClass.Name);

From there, you can use System.schedule, though it may get you or someone else into a deeper conundrum down the road.

Schedulable instance = (Schedulable)Type.forName(execution.ApexClass.Name).newInstance();
system.schedule('Job No Longer Deleted', jobData.CronExpression, instance);

However, it may be preferable to simply interpret the CronExpression for yourself and still schedule through the UI. For example, if you scheduled it to execute at 1:00 PM each weekday, it would look like: 0 0 13 ? * 2,3,4,5,6. If it's scheduled through the UI in the first place, then you will get the hour from the third component, and the days of the week from the final component. 1 indicates Sunday, 2 indicates Monday, etc.

Related Topic