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
SF7SF7 

De-activate users after certain time

Hi 

 

Is there a way that all the users who are not logged in for 90 days be auto matically de-activated and we should exempt couple of users from it.

 

FYI 

i already tried using workflows but unfortunately we cannot do much on the User object with workflows.

 

Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
SF7SF7

here is my final code

 

global class deactivateUsers implements Database.Batchable<SObject>
{

   
   
        dateTime dt = date.today()-90;
       public String query = 'SELECT Name, LastLoginDate, Id From User WHERE IsActive = true AND LastLoginDate < +dt  and profile<>"System Adminstrator" ';
    

    global Database.querylocator start(Database.BatchableContext bc)
    {
       return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext bc,List<User> scope)
    {
        List<User> userList = new List<User>();
        
        for(User s:scope)
        {
            User u =(user)s;
            userList.add(u);
        }
        
        if(userList.size() > 0)
        {
            for(User usr : userList)
            {
                usr.isActive = false;
            }
        }
        update userList;
    }

    global void finish(Database.BatchableContext bc)
    {
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
                          FROM AsyncApexJob 
                          WHERE Id = :BC.getJobId()];

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Job Status: ' + a.Status);
        mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 

global class ScheduleDeactivateUsers implements Schedulable {

/* Input: NA
Process: The execute method instantiate's the DeactivateUsers.cls and is schedulable
through UI or apex code.

*/
global void execute(SchedulableContext ctx){
DeactivateUsers uu = new DeactivateUsers();
Database.executeBatch(uu);
}
}

All Answers

ShamilShamil

You can use 'Apex Scheduler' to schedule an apex class that would periodically check for users to be deactivated based on your criteria. You'd have to write some apex code for that.

Srikant JoshiSrikant Joshi


Create a Schedulable class and Run it with the below logic.

List<User> LstUser = new list<User>{};
for(User InactiveUser  :[select id from User where LastLoginDate<:System.now().addDays(90)]){// Query all users whose last login was 90 before.
    InactiveUser.IsActive = false;//Make'em inactive
    LstUser.add(InactiveUser);
    
}
update LstUser;//Update Users.

 



Hope this helps.

joshisrik@gmail.com
Senior Technical Analyst|Schneider Electric.

SamuelDeRyckeSamuelDeRycke
where LastLoginDate<:System.now().addDays(90)])

 Probably just a typo, but that would give quite the unexpected outcome.

 

This might be more appropriate :)

 

addDays(-90)

 

 

SF7SF7

Hi Srikanth

 

Thanks for the reply and the code i am gona try that 

SF7SF7

Thanks Shamil for the reply and i got the idea i totally forgot about that option , ofcourse i never used it until now i am gona try that 

SF7SF7

Thanks Sdry

SF7SF7

here is my final code

 

global class deactivateUsers implements Database.Batchable<SObject>
{

   
   
        dateTime dt = date.today()-90;
       public String query = 'SELECT Name, LastLoginDate, Id From User WHERE IsActive = true AND LastLoginDate < +dt  and profile<>"System Adminstrator" ';
    

    global Database.querylocator start(Database.BatchableContext bc)
    {
       return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext bc,List<User> scope)
    {
        List<User> userList = new List<User>();
        
        for(User s:scope)
        {
            User u =(user)s;
            userList.add(u);
        }
        
        if(userList.size() > 0)
        {
            for(User usr : userList)
            {
                usr.isActive = false;
            }
        }
        update userList;
    }

    global void finish(Database.BatchableContext bc)
    {
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
                          FROM AsyncApexJob 
                          WHERE Id = :BC.getJobId()];

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Job Status: ' + a.Status);
        mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 

global class ScheduleDeactivateUsers implements Schedulable {

/* Input: NA
Process: The execute method instantiate's the DeactivateUsers.cls and is schedulable
through UI or apex code.

*/
global void execute(SchedulableContext ctx){
DeactivateUsers uu = new DeactivateUsers();
Database.executeBatch(uu);
}
}

This was selected as the best answer
suvarna vennapusalasuvarna vennapusala
08/11/2019
POA:
My work today 
-->Create a Application to Add the custom record details and 
display details same page using lightning component.
-->create BatchApex class that check project has still active 
and close date is equal the night,set the project to in-active.
Thanks.
suvarna vennapusalasuvarna vennapusala
08/11/2019
POA:
My work today 
-->Create a Application to Add the custom record details and 
display details same page using lightning component.
-->create BatchApex class that check project has still active 
and close date is equal the night,set the project to in-active.
Thanks.
Pooja K MPooja K M
How can I achieve the above  Situation without using code.Is there any other way to achieve it?
EnergizerEnergizer
In reviewing the code, I have a couple questions regarding the 'Best answer chosen by Admin.' 
  1. How does this solution work when the IsActive field is not selected in the query?
  2. Why would you need to add everything to a list then check that new list size and loop through the same values?
  3. Why not just implement the main class to also be schedulable?
  4. Why not use strongly typed SOQL?