[SalesForce] Delete Old Scheduled Jobs from Batch Class

I'm having a batch class which gets reschedule after 5 mins and delete old scheduled jobs which has already executed.But i'm unable to delete old jobs and in debug log i'm getting error:"Exception in deleting job : Only CronTrigger IDs and batch, future, and queueable job IDs are supported.".Below is the Code I'm using in my finish method :

global void finish(Database.BatchableContext BC)
{
     Datetime dt = system.now().addMinutes(5);

    String day = string.valueOf(dt.day());
    String month = string.valueOf(dt.month());
    String hour = string.valueOf(dt.hour());
    String minute = string.valueOf(dt.minute());
    String second = string.valueOf(dt.second());
    String year = string.valueOf(dt.year());

    String strJobName = 'Send SMS Batch-' + String.valueof(dt);
    String strSchedule = '0 ' + minute + ' ' + hour + ' ' + day + ' ' + month + ' ?' + ' ' + year;

    if(!test.isRunningTest())
     system.schedule(strJobName, strSchedule, new VGA_ScheduleSendBatchSMS());

    List<CronTrigger> lstCron = [select Id, State, NextFireTime, CronJobDetailId from CronTrigger where NextFireTime = Null AND State = 'DELETED'];

    if(lstCron != Null && !lstCron.isEmpty())
    {
        try
        {
            for(CronTrigger obj : lstCron)  
            {
                system.abortjob(obj.CronJobDetailId);
            }
        }
        catch(Exception e)
        {
            system.debug('@@Exception in deleting job : ' + e.getMessage());
        }
    }
}`

Best Answer

To clean up the list, you can purge the old jobs:

global void finish(Database.BatchableContext BC)
  System.purgeOldAsyncJobs(Date.today());

You should only be calling System.abortJob to cancel jobs that have a future.

In the future, if you do need to abort a CronTrigger, use the Id value, not the CronJobDetailId:

for(CronTrigger ct:[SELECT Id FROM CronTrigger]) {
  System.abortJOb(ct.Id);
}
Related Topic