+ Start a Discussion
Bhushan Singh 13Bhushan Singh 13 

I have created one Batch Apex and scheduler class for execute on every 5 minute but this scheduler is not working , please help me

Hi,
I have created one Batch Apex and scheduler class for execute on every 5 minute but this scheduler is not working , please help me 
Batch Apex --

global class BatchApexUpdateDemo implements Database.Batchable<sObject>
{

    global  Database.QueryLocator start(Database.BatchableContext con)
     {
      String query ='select Id, First_Name__c, Company__c , from User__c, Descriptiom__c';
      return Database.getQueryLocator(query);
    
     }
     
     global  void execute(Database.BatchableContext con, List<User__c> scope) {
     
         List<User__c> usrlist = new List<User__c>();
         for(User__c usr : scope )
          {
           usr.Descriptiom__c = usr.First_Name__c+' '+usr.Company__c;
           usrlist.add(usr);
          }
      
           update usrlist;
     }
     
     public void finish(Database.BatchableContext BC) 
     {
     
     
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors,
        JobItemsProcessed,TotalJobItems, CreatedBy.Email
        FROM AsyncApexJob WHERE Id =:BC.getJobId()];
        String UserEmail = 'bhushansingh226@gmail.com';
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {UserEmail});
        mail.setReplyTo('rathore.bhushan22@gmail.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }
}

Schedular class ---

global class schduleBatchOfUser implements Schedulable {

   global void execute(SchedulableContext ctx) {
     
     BatchApexUpdateDemo p = new BatchApexUpdateDemo();
      database.executeBatch(p);
      String sch1 = '0 5 * * * ?';
      
      schduleBatchOfUser sch2 = new schduleBatchOfUser();
      system.schedule('Every Hour plus 0 min', sch1, sch2);

      
   }   
}
Best Answer chosen by Bhushan Singh 13
Agustina GarciaAgustina Garcia
Hi I have tried, with minimun changes in your code and it works fine for me. Find below my code.
 
/**
 * Database.executeBatch(new BatchTestClass(), 200);
 * */
global class BatchTestClass implements Database.Batchable<sObject>
{
    global  Database.QueryLocator start(Database.BatchableContext con)
	{
		String query ='select Id, Name from User';
		return Database.getQueryLocator(query);
	}
     
	global  void execute(Database.BatchableContext con, List<SObject> scope)
    {
		Integer counter = 1;     
		List<User> usrlist = new List<User>();
		for(User usr : (List<User>)scope)
		{
            usr.Description__c = usr.Name + ' Description_' + counter;
            counter++;
            usrlist.add(usr);
		}
      
		update usrlist;
	}
     
     public void finish(Database.BatchableContext BC) 
     {
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors,
        JobItemsProcessed,TotalJobItems, CreatedBy.Email
        FROM AsyncApexJob WHERE Id =:BC.getJobId()];
        String UserEmail = 'bhushansingh226@gmail.com';
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {UserEmail});
        //mail.setReplyTo('rathore.bhushan22@gmail.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }
}
 
/**
 * Database.schedule('My First Schedule', '0 5 * * * ?', new schduleBatchOfUser())
 * */
global class schduleBatchOfUser implements Schedulable
{
	global void execute(SchedulableContext ctx)
    {
		BatchTestClass p = new BatchTestClass();
		Database.executeBatch(p);
		String sch1 = '0 5 * * * ?';
      
		schduleBatchOfUser sch2 = new schduleBatchOfUser();
		system.schedule('Every Hour plus 0 min', sch1, sch2);
   }   
}


Then, from developer console I run this: 
 
System.schedule('My First Schedule', '0 5 * * * ?', new schduleBatchOfUser());

If I go to Schedule Jobs in the org, I can see the job. Please take into account that depending on your org time, maye it is executed an hour later.

User-added image
And if I go to Apex Job screen I can see the job queued.

User-added image

Double check the org. Maybe you think it is not working because it takes longer than you expect.

Agustina

All Answers

Agustina GarciaAgustina Garcia
Taking a quick look, I have realiazed that your batch process doesn't look fine.  You cannot create a SOQL against 2 objects
 
String query ='select Id, First_Name__c, Company__c , from User__c, Descriptiom__c';

It should be
 
String query ='select Id, First_Name__c, Company__c , from User__c;

Double check first that your async job works by itself. After that check your schedule job.
Agustina GarciaAgustina Garcia
Sorry, second query should be: 
 
String query ='select Id, First_Name__c, Company__c from User__c';

 
Bhushan Singh 13Bhushan Singh 13
Hi Agustina,
 Thanks for helping, I did blunder mistake , but after written right query also it is not executting.
 String query ='select Id, First_Name__c, Company__c , Descriptiom__c from User__c';
Agustina GarciaAgustina Garcia
Hi I have tried, with minimun changes in your code and it works fine for me. Find below my code.
 
/**
 * Database.executeBatch(new BatchTestClass(), 200);
 * */
global class BatchTestClass implements Database.Batchable<sObject>
{
    global  Database.QueryLocator start(Database.BatchableContext con)
	{
		String query ='select Id, Name from User';
		return Database.getQueryLocator(query);
	}
     
	global  void execute(Database.BatchableContext con, List<SObject> scope)
    {
		Integer counter = 1;     
		List<User> usrlist = new List<User>();
		for(User usr : (List<User>)scope)
		{
            usr.Description__c = usr.Name + ' Description_' + counter;
            counter++;
            usrlist.add(usr);
		}
      
		update usrlist;
	}
     
     public void finish(Database.BatchableContext BC) 
     {
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors,
        JobItemsProcessed,TotalJobItems, CreatedBy.Email
        FROM AsyncApexJob WHERE Id =:BC.getJobId()];
        String UserEmail = 'bhushansingh226@gmail.com';
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {UserEmail});
        //mail.setReplyTo('rathore.bhushan22@gmail.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }
}
 
/**
 * Database.schedule('My First Schedule', '0 5 * * * ?', new schduleBatchOfUser())
 * */
global class schduleBatchOfUser implements Schedulable
{
	global void execute(SchedulableContext ctx)
    {
		BatchTestClass p = new BatchTestClass();
		Database.executeBatch(p);
		String sch1 = '0 5 * * * ?';
      
		schduleBatchOfUser sch2 = new schduleBatchOfUser();
		system.schedule('Every Hour plus 0 min', sch1, sch2);
   }   
}


Then, from developer console I run this: 
 
System.schedule('My First Schedule', '0 5 * * * ?', new schduleBatchOfUser());

If I go to Schedule Jobs in the org, I can see the job. Please take into account that depending on your org time, maye it is executed an hour later.

User-added image
And if I go to Apex Job screen I can see the job queued.

User-added image

Double check the org. Maybe you think it is not working because it takes longer than you expect.

Agustina
This was selected as the best answer
Bhushan Singh 13Bhushan Singh 13
Hi Agustina ,

Thanks to reply it is working for me.

Bhushan
Bhushan Singh 13Bhushan Singh 13
Hi Agustina,
If i execute through the developer console then its working fine, but After Schedule  BatchApex Scheduler class throug the user interface , its shwoing this Exception while its running and not working- -

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Debug Log:
38.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO
00:05:00.0 (592246)|USER_INFO|[EXTERNAL]|00528000005VI4W|bhushan.rathoure@tavant.com|Pacific Standard Time|GMT-08:00
00:05:00.0 (630500)|EXECUTION_STARTED
00:05:00.0 (635778)|CODE_UNIT_STARTED|[EXTERNAL]|01p2800000F2CFU|My First Schedule
00:05:00.0 (153932608)|EXCEPTION_THROWN|[10]|System.AsyncException: The Apex job named "Every Hour plus 0 min" is already scheduled for execution.
00:05:00.0 (154136851)|FATAL_ERROR|System.AsyncException: The Apex job named "Every Hour plus 0 min" is already scheduled for execution.

Class.schduleBatchOfUser.execute: line 10, column 1
00:05:00.154 (154149727)|CUMULATIVE_LIMIT_USAGE
00:05:00.154 (154149727)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

00:05:00.154 (154149727)|CUMULATIVE_LIMIT_USAGE_END

00:05:00.0 (154186406)|CODE_UNIT_FINISHED|My First Schedule
00:05:00.0 (155826996)|EXECUTION_FINISHED
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Please let me know if you have any idea, 

Thanks & Regards
Bhushan 
Agustina GarciaAgustina Garcia
Hi,

Sorry for the late response. Actually with this call

System.schedule('My First Schedule', '0 5 * * * ?', new schduleBatchOfUser());
System.schedule('My First Schedule', '0 5 * * * ?', new schduleBatchOfUser());
The job will be executed periodically till you finish it, so I guess you don't need the second schedule call, so the class schduleBatchOfUser would be withouth lines between 10 to 13. 


 
Nitish TalekarNitish Talekar

Example, you have Scheduler class namely ScheduleBatchApexClassExample and want to run the schedule a class in every five mins,

Then Run below cron expression from your developer console:

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

Thanks,
Nitish
Agustina GarciaAgustina Garcia
Hi Bhushan

I posted this answer the 19th of Dec. but I just realized that I left my email in the answer so deleted it to avoid people could contact me directly.

This is the same response.

I have been testing and my previous response also failed with the same error message, but I made it work.

This is the Batch class
 
/**
 * Database.executeBatch(new BatchTestClass(), 200);
 * */
global class BatchTestClass implements Database.Batchable<sObject>
{
    global  Database.QueryLocator start(Database.BatchableContext con)
    {
        String query ='select Id, Name from User';
        return Database.getQueryLocator(query);
    }
     
    global  void execute(Database.BatchableContext con, List<SObject> scope)
    {
        Integer counter = 1;     
        List<User> usrlist = new List<User>();
        for(User usr : (List<User>)scope)
        {
            usr.Description__c = usr.Name + ' Description_' + counter;
            counter++;
            usrlist.add(usr);
        }
      
        update usrlist;
    }
     
     public void finish(Database.BatchableContext BC) 
     {
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors,
        JobItemsProcessed,TotalJobItems, CreatedBy.Email
        FROM AsyncApexJob WHERE Id =:BC.getJobId()];
        String UserEmail = 'bhushansingh226@gmail.com';
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {UserEmail});
        mail.setReplyTo('rathore.bhushan22@gmail.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }
}

This is the Schedule class
 
/**
 * Database.schedule('My First Schedule', '0 5 * * * ?', new schduleBatchOfUser())
 * */
global class schduleBatchOfUser implements Schedulable
{
    global void execute(SchedulableContext ctx)
    {
        BatchTestClass p = new BatchTestClass();
        Database.executeBatch(p);
   }   
}

And you would also need a way to execute it every 5 minutes. I have created another class to make these calls
 
public with sharing class RunScheduleJobService
{
    public static void runScheduleJobProcess()
    {
        System.schedule('Job at 0 minutes', '0 0 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 5 minutes', '0 5 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 10 minutes', '0 10 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 15 minutes', '0 15 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 20 minutes', '0 20 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 25 minutes', '0 25 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 30 minutes', '0 30 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 35 minutes', '0 35 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 40 minutes', '0 40 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 45 minutes', '0 45 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 50 minutes', '0 50 * * * ?', new schduleBatchOfUser());
        System.schedule('Job at 55 minutes', '0 55 * * * ?', new schduleBatchOfUser());
    }
}

Once you have created the schedule, they will be repeated every hour by default. 

As Nitish says, you can also run the code into Dev Console, it is the same as my class, but having a class you can integrate in your code. If you need to run it from the Developer Console, do what Natish suggests or just make this call
 
RunScheduleJobService.runScheduleJobProcess();

I have also seen this post (https://developer.salesforce.com/forums/?id=906F00000008yFvIAI) in the forum but not sure how "the RecurringScheduleJob.startJob();" works

If this works for you, remove the "Solved" from the other answer and click on this one.

Agustina
 
Bhushan Singh 13Bhushan Singh 13
Thanks Agustina for helping. 

Thanks & Regards
BHushan Sigh