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
Jeff Bryant 16Jeff Bryant 16 

Batchable Apex to deactivate users after 90 days even if they are the Default Workflow User

I'm working on batchable Apex that will deactivate a user after 90 days without logging in the system. However, if a user hasn't logged in after 90 days and currently is the Default Workflow User, then the batch will fail. Is there any way to check for this or other things like it in code (Web-to-Case Owners or Web-to-Lead Default Creators) or is this something that manually has to be changed and can't be automated? 
AbhishekAbhishek (Salesforce Developers) 
Workflows will only fire whenever the record gets created or edited. You cannot achieve your requirement of deactivation of users using workflows. 

For your requirement, you need to make use of Batch Apex

==========================

APEX Code

public class DeactivateInactiveUsers implements Schedulable {
    public void execute(SchedulableContext context) {
        User[] selectedUsers = [SELECT Id FROM User WHERE IsActive = TRUE AND Id NOT IN (SELECT UserId FROM LoginHistory WHERE LoginTime = LAST_N_DAYS:90)];
        for(User record: selectedUsers) {
            record.IsActive = false;
        }
        Database.update(selectedUsers, false);
    }
}

Simply put this into your org, and set a daily schedule, and you're set.

================================


Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks.