Apex Test Method for Removing Scheduled Batches
Don't you really dislike when you go to deploy some code to a production Salesforce org and it fails because you forgot to unschedule a batch class? This is especially frustrating in a larger org where there is lots of code running and the deployment takes a long time due to the large number of @isTest methods that need to be run. I thought I would share some code that I wrote, which will remove any scheduled batch jobs and, therefore, avoid any issues with deployments in your orgs. Besides, who doesn't want to see more examples of @isTest Apex methods?
The code including comments is below:
/*
Created by: Greg Hacic
Last Update: 11 October 2012 by Greg Hacic
Questions?: www.interactiveties.com/contact
*/
@isTest
private class testSomeBatchProcess {
@isTest //defines method for use during testing only
static void testLogic() {
removeCronTriggers(); //call the method that will remove the scheduled batches
//do the rest of your testing...
}
public static void removeCronTriggers() {
Set<Id> adminProfiles = new Set<Id>(); //set for holding the Ids of Profiles that have the PermissionsModifyAllData permission
for (Profile p : [SELECT Id FROM Profile WHERE PermissionsModifyAllData = true]) { //for all profiles where the PermissionsModifyAllData permission is True
adminProfiles.add(p.Id); //add the Id to our Set
}
User adminUser = [SELECT Id FROM User WHERE isActive = true AND ProfileId in : admin_profiles LIMIT 1]; //select an active user that has a valid admin profile
System.runAs(adminUser) { //run as the selected User
List<CronTrigger> cronTriggersReadyToFireAgain = [SELECT Id FROM CronTrigger WHERE NextFireTime != null]; //create a list of CronTrigger records that are scheduled to fire again
if (!cronTriggersReadyToFireAgain.isEmpty()) { //if the list is not empty
for (CronTrigger t : cronTriggersReadyToFireAgain) { //for each record
System.abortJob(t.Id); //abort the job
}
}
}
}
}
Short post but I thought this would be useful to those of you that use batch Apex in your Salesforce orgs.