+ Start a Discussion
Force.comForce.com 

Help needed in Batch apex

 After running a Batch script, a New Apex job gets created. So Whenever I run the batch again, it throws an exception saying:

"The Apex job named "New Job" is already scheduled for execution".

 

then I delete the existing Apex job from Setup -> Monitoring -> Scheduled jobs to resolve the exception.

I need to delete the existing apex jobs automatically once they are completed.  

Are there any possible workarounds for this? 

 

Plz help, its urgent

Ritesh AswaneyRitesh Aswaney

You could hold on to the ids of the scheduled jobs and pass them into a System.abortJob call before scheduling your new jobs.

 

System.abortJob(jobId)

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_system.htm

Force.comForce.com

Thanks for reply.

 

In the finish method I tried to abort the apex scheduled job but the next time whenevr I run the batch, previous job still exists in the database.

 

How shall I get the existing jobIds?

Rahul S.ax961Rahul S.ax961

Hello,

 

I would like to tell, that Schedulars and Batches are different concepts.

there Batch can be scheduled only once, but it can be called multiple times.

I think instead of Executing batch you are Executing Schedular.

Let me know if you dont get it.

 

Thanks

symantecAPsymantecAP

Hi ALL i am running thru same issue.. My requirement is to run the batch every 15 mins and i ger error all the time that my

 

The Apex job named "Schedule Job1" is already scheduled for execution."

 

Below  is my code.

 

global class updateOpportunityStage implements Database.Batchable<sObject>,Schedulable{
global string query ;

global updateOpportunityStage(){

Query = 'Select Id,BigMachines__Status__c  from BigMachines__Quote__c' ;

}

global database.querylocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);    
}
    global void execute(SchedulableContext SC){
        updateOpportunityStage stg = new updateOpportunityStage();
        //String SCHEDULE_NAME = 'Process Quotes'; 
        //id cronid = System.schedule(SCHEDULE_NAME, '0 0 * * * ?', stg); 
        
       String sch = '0 15 * * * ?';
System.schedule('Schedule Job1', sch,stg);

  updateOpportunityStage stg2 = new updateOpportunityStage();
String sch2 = '0 15 * * * ?';
System.schedule('Schedule Job2', sch2, stg2);

        updateOpportunityStage stg3 = new updateOpportunityStage();
String sch3= '0 30 * * * ?';
System.schedule('Schedule Job3', sch3, stg3);

        updateOpportunityStage stg4 = new updateOpportunityStage();
String sch4 = '0 45 * * * ?';
System.schedule('Schedule Job4', sch4, stg4);

        
        
        
      //  System.abortJob(cronid);
//String cronStr =Datetime.now().addSeconds(10).format('s m H d M ? yyyy');
     //  System.schedule('Process Quotes', cronStr, stg);
        //System.abortJob(cronstr);
        
       /* String hour = String.valueOf(Datetime.now().hour());

String min = String.valueOf(Datetime.now().minute());

String ss = String.valueOf(Datetime.now().second());

String nextFireTime = ss + ' ' + min + ' ' + hour + ' * * ?';

system.schedule('Start me once', nextFireTime, stg); */
        database.executebatch(stg);
        
    }

global void execute(Database.BatchableContext BC, List<sObject> scope){

     
        Set<id> liOppIds = new Set<id>();
//List <Opportunity> oppList = new List<Opportunity>() ;
for(sObject s : scope){

BigMachines__Quote__c quote = (BigMachines__Quote__c)s;
System.debug('Adil'+quote);
if(quote.BigMachines__Status__c == '*unison*' && quote.BigMachines__Is_Primary__c == true)
liOppIds.add(quote.BigMachines__Opportunity__c);

}


//query all the opportunities in a single query
List<Opportunity> opp = new List<Opportunity>();
opp = [select id, StageName from Opportunity where id in :liOppIds and stagename != 'Closed Won'];
for ( Opportunity opps : opp)
{
opps.StageName = 'Closed Won' ; 
}
//update all opportunities in a single DML
if(opp.size() > 0)
update opp;
 
    }
  global void finish(Database.BatchableContext BC){}  

}

 thanks

Force.comForce.com

Hi symantecAP,

 

I also faced the same problem. I tried to delete the Scheduled jobs programmatically but it is not supported through apex. So each time I made a call, I called the Schedulable Batch Class with a different Apex Job name. I tried to change the name of the Apex Job dynamically. Code snippet is:

 

<Your Schedulable Class> h = new <Your Schedulable Class>();
DateTime todayMin = Datetime.now();
DateTime today = todayMin.addMinutes(1);
        
String seconds = '0';
Integer minutes = today.minute();
Integer hours = today.hour(); 
Integer dayOfMonth = today.day(); 
Integer month = today.month(); 
Integer milisec = today.millisecond();
String dayOfWeek = '?'; 
Integer year = today.year(); 

String sch = seconds + ' ' + minutes + ' ' + hours + ' ' + dayOfMonth + ' ' + month + ' ' + dayOfWeek + ' ' + year;
     
String j = 'New Job:'+hours+':'+minutes+':'+seconds+':'+milisec;

system.schedule(j, sch, h);

 

All the finished Scheduled Jobs are deleted automatically after a certain period of time.

 

Please try the above workaround. I hope it will help.

 

Thanks,

Pragati

symantecAPsymantecAP

Hi Pragati

 

Thank you so much for the reply. If I understand it clearly this code snippet is to schedule the class every minute?

How do I dynamically change the Apex job name and lets say once they get killed, can they be restarted? coz it has to run every 15 mins round the clock .

ANd how would it kill the job without system.abort ( jobid)

 

Thanks

Adil

Force.comForce.com

Hi symantecAP,

 

I scheduled the batch for every minute. You can schedule it to run after every 15minutes with different job name. Each time you make a call to Batch, a new Apex job will be created.

I tried to kill the job using system.abort ( jobid). But still I could see the Job exists in the Schedule Jobs List. That was the reason I created new Job with different name in every minute through code.

 

I don't exactly remember now but somewhere it was written in the documentation that Apex jobs automatically get deleted after 20 days(Not sure) from the Schedule Jobs List in the Setup.

 

Thanks,

Pragati

symantecAPsymantecAP

Hi Pragati

 

I understood the trick , This is awsome so far.. I scheduled it now.  Its scheduled every min. will let you know if i run in to some errors.. U r a saviour

Tushar Arora 20Tushar Arora 20
Hi Just as a Info, the limit of 100 scheduled apex jobs is on the scheduled jobs which need to be executed in future. This 100 does not count those scheduled jobs that have executed and got completed and have no next schedule but are still visible when we go to the "Scheduled Apex Jobs View".