Search code examples
salesforceapexapex-code

Can a CronTrigger Job ID be used to determine if a job had been aborted or is invalid?


I have a function that gets called as part of reschedule logic in an Apex class that implements implements System.Schedulable.

@TestVisible private void reschedule(CronTrigger me, ISchedulable item, MySchedulableContext myCtx) {
        try {
            System.abortJob(me.Id);
        } catch(Exception e) {
            System.debug('Unable to abort the job');
        }
        String newTrigger = item.getNextTriggerString(myCtx);
        if (newTrigger != null && newTrigger.length() > 0) {
            try {
                System.schedule(me.CronJobDetail.Name+ '-' + System.currentTimeMillis(), newTrigger, this);
            } catch(Exception e) {
                System.debug('Unable to start the job');
            }

        }
    }

How would I know if the job I am about to abort is not already aborted or if the job I am about to start is not already started? Yes the try/catch will take care of errors however I would like to understand this better


Solution

  • You can query the AsyncApexJob Object to get the status of the job.

    You could do something like this:

    SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
    FROM AsyncApexJob WHERE ID = :jobId
    

    Then check the status if you would like. The available status are the following:

    • Holding
    • Queued
    • Preparing
    • Processing
    • Aborted
    • Completed
    • Failed

    So if Status is Aborted the job has been aborted already.