Salesforce Schedule Batch

This script helps you to schedule/deschedule current Apex Batch Jobs

				
					String NameOfBatch = 'Name Of Batch';
Set<String> existingJobNames = new Set<String>();
List<CronTrigger> existingScheds = [SELECT Id, CronJobDetail.Name FROM CronTrigger WHERE CronJobDetail.JobType = '7'];
for (CronTrigger ct : existingScheds)
{
	existingJobNames.add(ct.CronJobDetail.Name);
}
if (!existingJobNames.contains(NameOfBatch)){
	NameOfBatch_Sch b = new NameOfBatch_Sch();
	String sch_b = '0 0 9 ? * 1,2,3,4,5,6,7';
	System.schedule(NameOfBatch, sch_b, b);
}
//#### DESCHEDULE BATCH ####
String NameOfBatch = 'Name of batch';
Set<String> jobNames = new Set<String>{		
	NameOfBatch};
List<CronTrigger> cronTriggers = [SELECT Id,TimesTriggered, NextFireTime, CronJobDetail.Id, CronJobDetail.Name, CronJobDetail.JobType
								  FROM CronTrigger where CronJobDetail.JobType = '7' AND CronJobDetail.Name IN :jobNames
									ORDER BY CreatedDate DESC];
if (cronTriggers.isEmpty()){
	system.debug('Non è stato trovato nessun processo Apex schedulato. Impossibile deschedulare.');
}
for (CronTrigger ct : cronTriggers){
	System.abortJob(ct.Id);
}				
			

Leave a Reply

en English
en Englishfr Frenchde Germanit Italian