I have written a scheduler for deactivating salesforce users who doesn't logged in for last 90 days. The code is working as expected if I remove exception logging into a salesforce object at line #14. When I put this facing Mixed DML operation (Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you...)
Please help me to resolve this exception.
public class DeactivateInactiveUsers implements Schedulable {
public void execute(SchedulableContext context) {
try{
List<string> toAddress = new List<string>();
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;
toAddress.add(record.email);
}
Database.update(selectedUsers, false);
}
catch(System.Exception e) {
String strException = 'Exception Type: ' + e.getTypeName() + '-Message: ' + e.getMessage() + '-Cause: ' + e.getCause() + '-Line Number: ' + e.getLineNumber() + '-Stack Trace: ' + e.getStackTraceString();
ErrorloggingClass.logErrors(strException, 'DeactivateUser');
}
}
}