[SalesForce] Scheduled Batch Apex Hangs in Queued Status

This is my first crack at a scheduled batch Apex class. Copied the code from the manual but missing something. When I run class MassDeleteSchedules in Anonymous block, it works fine. But when I use the UI to schedule it it just hangs in queued status. I gave it a couple hours and nothing changed so cancelled it. There's only 1 batch that's being scheduled.

I feel like the last 2 lines are causing the issue.

global class JobScheduler implements Schedulable{
global void execute(SchedulableContext scMain){
    CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
                      FROM CronTrigger WHERE Id = :scMain.getTriggerId()];

    System.debug(ct.CronExpression);
    System.debug('Number of times batch triggered '+ ct.TimesTriggered);

    //Ensure batch not already triggered
    System.assertEquals(0, ct.TimesTriggered);

    // Sets up query for time period to remove records
    Date dt = Date.today();
    dt = dt.addMonths(-1);
    String dateStr = String.valueOf(dt); // Passing as string for dynamic query below

    String e = 'ONE__Schedule__c';
    String f = 'ONE__Start_Date__c';
    String v = null;
    String q = 'Select id, name from ' + e + ' where ' + f + ' < ' + dateStr;

    MassDeleteRecords del = new MassDeleteRecords(q,e,f,v);       
    Id idbatch = Database.executeBatch(del,2000);
   }
 }

Best Answer

Scheduled Batch Apex jobs appears as Queued status in the Apex Jobs page until the time comes to execute the job (i.e. as per the time you scheduled it to run).

Could it be that you had scheduled it to run by your local clock but the Salesforce time is different and the Job was never actually due to start yet (and hence it will be correctly showing Queued status)?

I see you have put some debug code in the execute() method, did you ever see that in your debug logs? If not, I'd suggest that your Job never even started.