+ Start a Discussion
Ken KoellnerKen Koellner 

Is there a way to delete a Schedule batch apex job programmatically.

I can call System.schedule() to schedule a job.


Is there any way to query the job list and delete jobs programmactically from Apex?



The docs say System.abortJob() is the method you need. I would test it out but looks like that is what you want.

Ken KoellnerKen Koellner

The question is how to get the id of a job.


What I want to do is delete a job that has already run and will not be run again.  How can it be found?  I don't think it will be in CronTrigger.


If you filter by State you will get active jobs. I haven't read anything that says you can't query active jobs.

Ken KoellnerKen Koellner

Actually what I want to do is find completed jobs and delete them.


I wish the name of the job where exposed in CronTrigger but it is not.  That would make it easy.


I scheduled a bunch of jobs that have a single run time and let them run and then looked at crontrigger.  I can see that they show up with state = 'delete' and timestriggered = 1.


I could go and delete any jobs in that state, which could grab more than I want which might or might not be harmless.  The owner id is there in the table so I could put all the jobs I care about under a specific owner and then query for that also.


What I really want to do is have a job that will schedule another copy of itself if it has more work to do.  It starts once a day, processes up to 100 transactions, then, if there is additional work today, queues another copy if itself to start in five minutes. 


The problem with this is the jobs add up and the limit of 10 is exceeded.  If I could find the previously run job, I could delete it.  It's a bit of a kludge but it would work.


(I know you are problem thinking, use the scheduler to call batch apex but there's numerous reasons why batch apex won't work including callouts and @future calls)



'Creative Solution Problem Solving Skills' should be the first line of any Apex developer's resume.


you can do something like this



for(CronTrigger ct : [SELECT id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger]){