function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
StoneShot_GazStoneShot_Gaz 

Abort schedule job in 'Waiting' status using Apex

Hi there

Is there a way of aborting a scheduled job that is currently in the 'Waiting' status? I have an Apex controller which is designed to create/update a schedule based on the settings provided by the user (in this case a system administrator). The schedule controls sync between SalesForce and an external web service.

The schedule is recurring on a daily or weekly basis, I have tried using the System.abortJob() method to abort the job but this does nothing. Since I cannot abort the job, I then cannot re-schedule the job with the same name. Scheduling under a new name would soon run into trouble due to limits.

//TEST
schedule = '0 40 */2 * * ?';

if (scheduleId.Value__c != '') {
            List<CronTrigger> ct = [select Id from CronTrigger where Id = :scheduleId.Value__c];
            
            if (ct.size() > 0) {
            	for (CronTrigger c : ct) {
            	system.debug('attempt to abort job');
                system.abortJob(c.Id);
                system.debug('job aborted');
            	}
            }
        }
        
        ScheduledSync sSync = new ScheduledSync();
        String syncResult = system.schedule('Sync', schedule, sSync);
        
        scheduleId.Value__c = syncResult;
        
        update scheduleId;

 
Any help would be greatly appreciated.

Regards
Gaz

 

lakslaks

Hi Gaz,

 

Posting a code snippet that I had tried, and it worked fine in deleting jobs in 'WAITING' state. Hope it helps.

 

List<CronTrigger> listCronTrigger = [select Id, CronExpression, EndTime, NextFireTime, OwnerId,
        PreviousFireTime, StartTime, State, TimesTriggered, TimeZoneSidKey from CronTrigger 
        where State = 'Waiting'];
        
        System.debug('No of jobs: '+listCronTrigger.size());
        If (listCronTrigger.size() > 0)
        {
           for (Integer i = 0; i < listCronTrigger.size(); i++)
           { 
                System.abortJob(listCronTrigger[i].Id);
                System.debug('Job details ::'+String.valueOf(listCronTrigger[i]));
           }
        }
    

 

Regards,

Lakshmi.

missonjaraemissonjarae

laks, did you execute that in developer console?  I have a trigger that will not run (but was previously working) and debug log is giving me "waitingJobPage" status when I attempt to fire it.   

force_knightforce_knight

Hi Gaz,

 

A year and a half later.... I ran into the same issue as you did.

 

The problem was not related to the job status, it was related to the context of the abort call. When you call System.abort inside DML transaction, it won't get aborted. Abort will silently fail without any error message. 

 

I put System.abort() before DML and it worked like a charm!

 

Hope this helps someone...