Deleting a scheduled Apex job

abortjobscheduled-job

I have a scheduled job name with which I can query the same by using this:

SELECT Id, CronExpression, OwnerId, State, TimesTriggered, CronJobDetail.Name, CronJobDetail.Id, CronJobDetail.JobType FROM CronTrigger where CronJobDetail.Name = 'My job name'

I need to delete this job (any scheduled ones plus must not schedule any more in future), so as I understand from this answer here, I may delete this record from CronTrigger or use System.abortJob().

However, I fail to understand which Id I must pass to the System.abortJob. Is it the CronTrigger.Id or the CronJobDetail.Id? The Id in the Apex Job Id column under Setup > Apex Jobs doesn't match with any of these 2 Ids. Is the Apex Job Id the Id that I need to pass to the System.abortJob(jobId) instead? I went through System.abortJob documentation but unfortunately I am still confused.

My next question, what is a way of finding the mapping between the CronTrigger/CronJobDetail and the Apex Job Id (displayed in Setup > Apex Jobs)? I so far have found a way to view it only from the UI.
Or is there no way of retrieving it if I myself havn't scheduled the job and stored the returned Id?

Note: I have no other information about the Job other than its name (not even the Apex class name).

Best Answer

It's just the Id for the job.

CronTrigger jobRecord = [SELECT  Id FROM CronTrigger  where CronJobDetail.Name = 'My job name'];
System.abortJob(jobRecord.Id);

To figure out which is which, you can query various details:

SELECT CronJobDetail.Name, CronExpression, NextFireTime
FROM CronTrigger

By the Apex Job Id, I presume you're talking about the list of executed asynchronous code bits, which means you're looking at the AsyncApexJob values. There is no relationship between AsyncApexJob and CronTrigger, as the former is just a log of executed asynchronous jobs (including future, queueable, and batchable jobs).

Related Topic