function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Surender reddy SalukutiSurender reddy Salukuti 

Batch and schedule

Hi ,

we are writting Batchapex and schedule apex programs in developer console and we are executing this batch apex and scheduleapex programs using Debug(open Execute Anonymous window).
But in real time project where we can Execute this programs please tell me answer if you know.

Thanks
Surender
 
Syed Insha Jawaid 2Syed Insha Jawaid 2
Hi Surender

There are two ways to schedule a batch class :
1. Using Cron Expression.(That needs to be executed once from anonymous window)
2. Schedule the apex classes from setup menu.

For reference : https://trailhead.salesforce.com/en/content/learn/modules/asynchronous_apex/async_apex_scheduled

Cheers!!!
Abdul KhatriAbdul Khatri
Here is the way you can do, I am explaining with examples
Let say you have a BatchApex
global class SampleBatch implements Database.Batchable<sObject> {
  private final String initialState;
  String query;
  
  global SampleBatch() {
      query = 'SELECT Id, Name FROM Account LIMIT 1';
  }

  global Database.QueryLocator start(Database.BatchableContext BC) {
    // Access initialState here 
    
    return Database.getQueryLocator(query);
  }

  global void execute(Database.BatchableContext BC, List<Account> batch) {
    // Access initialState here 
      for(Account acct : batch) {
          system.debug(acct.Name);
      }
    
  }

  global void finish(Database.BatchableContext BC) {
    // Access initialState here    
  }

}
You create a schedule class to schedule this Batch Apex
global class scheduledBatchable implements Schedulable {
   global void execute(SchedulableContext sc) {
      SampleBatch b = new SampleBatch(); 
      database.executebatch(b);
   }
}
Here is the way to schedule
User-added image

User-added image

This is a very basic way to schedule any Batch Apex
Raj VakatiRaj Vakati
Generally how we will execute the scheduler jobs is based on how frequently we want ro run the job

If we want to run every hr or less then we will go for the  Cron Expression and run from the developer console 



After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The System.Schedule method uses the user's timezone for the basis of all schedules, but runs in system mode—all classes are executed, whether or not the user has permission to execute the class.
 
RemindOpptyOwners reminder = new RemindOpptyOwners();
// Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
String sch = '20 30 8 10 2 ?';
String jobID = System.schedule('Remind Opp Owners', sch, reminder);

You can also schedule a class using the user interface.
  1. From Setup, enter Apex in the Quick Find box, then select Apex Classes.
  2. Click Schedule Apex.
  3. For the job name, enter something like Daily Oppty Reminder.
  4. Click the lookup button next to Apex class and enter * for the search term to get a list of all classes that can be scheduled. In the search results, click the name of your scheduled class.
  5. Select Weekly or Monthly for the frequency and set the frequency desired.
  6. Select the start and end dates, and a preferred start time.
  7. Click Save.



 
Abdul KhatriAbdul Khatri
Here are the ways you can do, I am explaining with examples

Let say you have a BatchApex
global class SampleBatch implements Database.Batchable<sObject> {
  private final String initialState;
  String query;
  
  global SampleBatch() {
      query = 'SELECT Id, Name FROM Account LIMIT 1';
  }

  global Database.QueryLocator start(Database.BatchableContext BC) {
    // Access initialState here 
    
    return Database.getQueryLocator(query);
  }

  global void execute(Database.BatchableContext BC, List<Account> batch) {
    // Access initialState here 
      for(Account acct : batch) {
          system.debug(acct.Name);
      }
    
  }

  global void finish(Database.BatchableContext BC) {
    // Access initialState here    
  }

}




One Way to Schedule by using Setup

Create a Schedul Class
global class scheduledBatchable implements Schedulable {
   global void execute(SchedulableContext sc) {
      SampleBatch b = new SampleBatch(); 
      database.executebatch(b);
   }
}
Here is the way to Schedule from Setup
User-added image

User-added image

Here is the way to Schedule from anonymous window
scheduledMerge m = new scheduledMerge();
String sch = '20 30 8 10 2 ?';
String jobID = system.schedule('Merge Job', sch, m);

Read in detail about how to undersand for sheduling periods
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm 



Second Way to Schedule by Intervals

Create a schedule class like this
global class scheduledBatchable2 implements Schedulable
{
	public static String jobName = 'My Sample Job';

	global class JobException extends Exception{}

	global void execute(SchedulableContext SC)
	{
      SampleBatch b = new SampleBatch(); 
      database.executebatch(b);
	}    
    
	/**
	* Schedule the execution of this job
	*/
	public static void start()
	{
		if(!getJobs().isEmpty()) {
			throw new JobException('Job already is started: ' + jobName);
		}

		System.schedule(jobName + ' 1',  '0 00 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 2',  '0 05 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 3',  '0 10 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 4',  '0 15 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 5',  '0 20 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 6',  '0 25 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 7',  '0 30 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 8',  '0 35 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 9',  '0 40 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 10', '0 45 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 11', '0 50 * * * ?', new scheduledBatchable2());
		System.schedule(jobName + ' 12', '0 55 * * * ?', new scheduledBatchable2());
	}

	public static void stop()
	{
		List<CronJobDetail> jobs = getJobs();

		if (!jobs.isEmpty()) {
			for(CronJobDetail job : jobs) {
				Id jobId = [SELECT Id from CronTrigger WHERE CronJobDetailId = :job.Id][0].Id;
				System.abortJob(jobId);
			}
		}
	}

	public static List<CronJobDetail> getJobs()
	{
		List<CronJobDetail> jobs = [SELECT Id FROM CronJobDetail WHERE Name LIKE :jobName+'%'];

		return jobs;
	}

}
In the Developer Console in 
   Debug --> Open Execute Anonymous Window, write this

To start 
scheduledBatchable2.start()
To Stop
scheduledBatchable2.stop()

Once you scheduled you should be able to see the scheduled Job here

User-added image

I hope this help you understand better.