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
DritterDritter 

Batch Apex - Queued Status

I wrote the following batch apex but it keeps getting stuck in a queued status when I schedule it?
 
global class KapUserCleanUp implements Database.Batchable<sObject>{

    datetime myDateTime = datetime.now();
    datetime newDateTime = myDateTime.addDays(-1);
    datetime inactiveDateTime = myDateTime.addDays(-90);

    //System.debug('current time: ' + myDateTime);
    //System.debug('newDateTime time: ' + newDateTime);
    //System.debug('inactiveDateTime time: ' + inactiveDateTime);

global Database.querylocator start(Database.BatchableContext BC){
            return Database.getQueryLocator([SELECT Email,Id,LastLoginDate FROM User WHERE ((IsPortalEnabled = True AND IsActive = true AND CreatedDate = :newDateTime) OR (IsPortalEnabled = false AND isActive = true AND lastLoginDate < :inactiveDateTime AND LastName != 'Site Guest User'))]);}

global void execute(Database.BatchableContext BC, List<User> users){
   System.debug('Users retrieved ' + Users);
   
   for (User u : users) {
       u.isActive = false;
       System.debug(u.id + ' ' + u.email + ' will be deactivated' + u.lastLoginDate);
   }
       Database.SaveResult[] srList = Database.update(users, false);
          for (Database.SaveResult sr : srList){
             if (!sr.isSuccess()) {
             //Operation failed, so get all errors
                for(Database.Error err : sr.getErrors()){
                     System.debug('The following error has occurred.');
                     System.debug(err.getStatusCode() + ': ' + err.getMessage());
                } 
             }  
          }
    }
   global void finish(Database.BatchableContext BC){
       }
   }

 
William LópezWilliam López

Hello Dritter,

According to a Salesforce documentation "When you call Database.executeBatch, Salesforce only adds the process to the queue. Actual execution may be delayed based on service availability."

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

In the practice I see long waits when it's a lot of data, have other batch already running, or users are editing the records that you want to update in the batch.

I would suggest to reduce the scope to a couple of records and see how it goes, after couple of time you will runs you will have some stats and will know best size and time to run the batch.

Make sure no other batch are running or wait for them to finish.

Also check this link an others in the forum, there are good tips to improve batch behaviour 

https://developer.salesforce.com/blogs/engineering/2013/02/force-com-batch-apex-and-large-data-volumes.html

Regards,

Bill