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
Kunal Purohit 4Kunal Purohit 4 

I want to schedule my batch apex after 5 minutes. I have tried using cron,but not working... plz help

public class StatusPublished implements database.Batchable<sobject>,Schedulable{

    public void execute(Schedulablecontext sc)
    {
         string cron='0 2 * * * ?*';
        StatusPublished sp =new StatusPublished();
        system.schedule('updatepaper', cron, sp);
      //database.executeBatch(sp);
    }
        public database.QueryLocator start(database.BatchableContext bc)
    {
        string query='select id,Name,Status__c from Research_Paper__c';
        return database.getQueryLocator(query);
    }
        public void execute(database.BatchableContext bc,list<Account> acc)
    {
        List<Research_Paper__c> rlist=new list<Research_Paper__c>();
        for(Research_Paper__c rp: rlist)
        {
            if(rp.Status__c=='Paper registration Complete')
            {
                rp.Status__c='Published';
                rlist.add(rp);
            }
        }
        update rlist;
    }
    
     public void finish(database.BatchableContext bc)
    {
 
    }

 
David Zhu 🔥David Zhu 🔥
You can add the following code in finish method. This will schedule the job in 5 mins once the current schedule job finishes.
public void finish(database.BatchableContext bc) {

   String batchJobName = 'StatusPublished';    //you can change to your actual job name.

List<CronTrigger> cron = [SELECT Id,CronJobDetail.name FROM CronTrigger WHERE CronJobDetail.Name = :batchJobName  Limit 1];

            if (cron.size() > 0)
            {
                System.abortJob(cron[0].Id);
            }

            Datetime dt = System.now().addMinutes(5);
            string CRON_EXP = '0 ' + String.valueOf(dt.minute()) + ' ' + String.valueOf(dt.hour()) + ' ' + String.valueOf(dt.day()) +
                    ' ' + String.valueOf(dt.month()) + ' ? ' + String.valueOf(dt.year());
            system.debug('CRON_EXP:' + CRON_EXP);
            String jobId = System.schedule(batchJobName ,CRON_EXP,new StatusPublished ());
}

 
Kunal Purohit 4Kunal Purohit 4
Hi David, i tried it but still not working...
David Zhu 🔥David Zhu 🔥
You also need to change the scheduleable execute method to 

    public void execute(Schedulablecontext sc)
    {
        DataBase.executeBatch(new StatusPublished());
    }

You can test this by running the following script in developer console anoymous window.
DataBase.executeBatch(new StatusPublished());
Abhishek BansalAbhishek Bansal
Hi Kunal,

You can use this cron expression to schedule batch after every 5 minutes: 0 0/5 * 1/1 * ? *
Please use the below link to get the cron expression as per your requiremnet:
http://www.cronmaker.com/?1

Let me know if this works for you.

Thanks,
Abhishek Bansal.