In the past, I have created several posts related to Scheduled Jobs, CronTrigger and AsyncApexJob,
Automating the process of cancelling and rescheduling scheduled jobs in Salesforce
Package for canceling and rescheduling schedulable jobs
Salesforce Code to mass cancel all existing scheduled jobs
Salesforce bug with leading or trailing spaces in Job Name inside System.schedule method
Linking CronTrigger and AsyncApexJob objects after rescheduling.
Now I want to reconcile what I have found so far.
First of all, there is no standard way to connect CronTrigger to AsyncApexJob.
I have noticed that they usually have the same created date and made a package which matched them by created date.
Later I have found the issues with this approach.
- Sometimes, there may be difference between created date of CronTrigger record and AsyncApexJob record in one second.
- Sometimes, on sandboxes or if the production org have been split, the difference may be up to several years.
Now I am thinking about a different way… probably we could just retrieve two lists and match them by some different way?
SELECT a.Id, a.CreatedDate, a.Status, a.ApexClassId, a.ApexClass.Name, CreatedBy.Name FROM AsyncApexJob a where a.ApexClassId != null and Status = ‘Queued’
SELECT c.Id, c.TimeZoneSidKey, c.CreatedById, c.CreatedBy.Name, c.CreatedDate, c.CronExpression, c.CronJobDetail.Name FROM CronTrigger c WHERE c.CronJobDetail.JobType = ‘7’