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
Sai.MaharajpetSai.Maharajpet 

schedule a batch class it should run every week and should delete last week account records

global class DeleteAccountRecords implements Database.Batchable<sObject>{
    global DeleteAccountRecords(){
    }

    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([
            select Id
            from Account
            where CreatedDate = LAST_N_DAYS:7
            ]);
    }

    global void execute(Database.BatchableContext BC, List<Account>scope){
        delete scope;
    }

    global void finish(Database.BatchableContext BC){
    }
}
 
global class Scheduler_class implements Schedulable{
    global void execute (SchedulableContext SC){
         DeleteAccountRecords b1 = new  DeleteAccountRecords();
       database.executeBatch(b1);
       string sch = '0 0 * * 0 ?';
       system.schedule ('Batch', sch, new Scheduler_class());
    }
}


Please correct me where I was going wrong

Thanks

Suraj MakandarSuraj Makandar
Hi Sai,

Your batch looks good, you can do the exeption handling if you want.

You need to update your cron expression to "0 0 0 * * 7", this will run every Sunday.

As per your need you can update the 7 with other number between 1-7 to run at any specific day.

Hope this helps!

Thanks,
Suraj

 
sachinarorasfsachinarorasf
Hi Sai,

I have gone through your problem.
 
Batch class:
global class DeleteAccountRecords implements Database.Batchable<sObject>{
    global DeleteAccountRecords(){
    }

    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([
            select Id
            from Account
            where CreatedDate = LAST_N_DAYS:7
            ]);
    }

    global void execute(Database.BatchableContext BC, List<Account>scope){
        delete scope;
    }

    global void finish(Database.BatchableContext BC){
    }
}

Schedule class:
global class Scheduler_class implements Schedulable{
    global void execute (SchedulableContext SC){
        DeleteAccountRecords b1 = new  DeleteAccountRecords();
        database.executeBatch(b1);
    }
    public static void scheduleJob()
    {
        string sch = '0 0 0 ? * MON *';
        system.schedule ('Batch', sch, new Scheduler_class());
    }
    
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Sachin Arora