|

Salesforce Development: Creating a Self-Scheduling Apex Class

Why This Is Useful

Have you ever wondered, “How do I effectively schedule an apex class to run every single minute of the day?” or maybe every hour or second (please don’t schedule anything every second, lol). Well there’s a great way to do it, by having your scheduled apex class reschedule itself! This method also significantly cuts down on the jobs you have to cancel to actually make any updates to your scheduled class as well. Say for instance you did schedule the class to run once a minute. That equates to 1440 scheduled jobs!! That’s a nightmare… with this method, you’ll only have one scheduled job but it will still run every minute of the day. Yay!

So let’s just get down to it… how does this magic work? It’s actually pretty simple. In your scheduled class you just find your currently running scheduled job, abort it and then reschedule it! Let’s check out the code below or on Github.


The Code

/**
 * @description An example of a continually rescheduling job.
 * @author Matt Gerry
 * @date 9/5/2020
 */

public with sharing class Repeating_Scheduler_Example implements Schedulable
{
	private final String JOB_NAME = 'Repeating Job';
	private final Integer ONE_MINUTE = 1;

	/**
    * @description The execute method fires each time the scheduler is run. Unless there is a
     constructor, this is always the first method to fire.
    * @param cont Schedulable context instantiated by the Schedulable implementation
    * @example System.schedule(JOB_NAME, cronExpression, new Repeating_Scheduler_Example());
    */
	public void execute(SchedulableContext cont)
	{
		new Repeating_Scheduler_Case_Insert().insertCase();
		findAndAbortJob(cont);
	}

	/**
	* @description Aborts the existing scheduled job. Then calls rescheduleJob to 
          reschedule this job.
	* @param cont Schedulable context instantiated by the Schedulable implementation
	* @example finaAndAbortJob(cont);
	*/
	private void findAndAbortJob(SchedulableContext cont)
	{
		if (cont == null)
		{
			return;
		}

		//Need to query CronJobDetail to find our currently active scheduled job
		List<CronJobDetail> cronDetail = [SELECT Id FROM CronJobDetail WHERE Name= 
                :JOB_NAME LIMIT 1];

		if (cronDetail.isEmpty())
		{
			return;
		}

		//Need to find the corresponding cron trigger to be able to abort the 
                //scheduled job
		List<CronTrigger> cronTriggers = [SELECT Id FROM CronTrigger WHERE 
                CronJobDetailId = :cronDetail[0].Id];

		if(cronTriggers.isEmpty())
		{
			return;
		}

		try
		{
			//Aborts the job current setup for this scheduled class
			System.abortJob(cronTriggers[0].Id);
			rescheduleJob();
		}
		catch (Exception e)
		{
			System.debug('This was the error ::: ' + e.getMessage());
		}
	}

	/**
	* @description Reschedules this job for one minute in the future.
	* @example rescheduleJob();
	*/
	private void rescheduleJob()
	{
		Datetime sysTime = System.now().addMinutes(ONE_MINUTE);
		String cronExpression = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' + 
                sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + 
                sysTime.year();
		System.schedule(JOB_NAME, cronExpression, new Repeating_Scheduler_Example());
	}
}

Aborting The Job

So as you can see from the above code, all we need to do is take the name of the job and query the CronJobDetail object to find the corresponding Cron Job for our scheduled apex and then we query the CronTrigger object to get that id so we can abort our scheduled apex’s next run. After getting the CronTrigger record Id we then utilize the System.abort method to abort our scheduled apex so that we can reschedule it.


Rescheduling The Job

After we abort the job we simply utilize the System.Schedule method to reschedule our class for a time in the future. In this code we just set it to one minute in the future via a variable, but I would suggest utilizing a custom metadata type to do this as it gives you the most flexibility.


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!


If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps



Similar Posts