>>>
global class Batchtoupdatelastloginoncontact implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC){
DateTime rightNow = DateTime.now();
DateTime d24hAgo = rightNow.addHours(-24);
string query='SELECT ContactId, LastLoginDate, LastPasswordChangeDate, Id FROM User where ContactId!=NULL and (NumberOfFailedLogins >0 OR LastLoginDate >=:d24hAgo)';
system.debug('String'+query);
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<User> userlist) {
Set<Id> setofuserid=new Set<Id>();
Map<Id,String> mapofstatus=new Map<Id,String>();
List<LoginHistory> lghlist=[SELECT Id, UserId, LoginTime, Status FROM LoginHistory where UserId in:userlist order by LoginTime desc];
for(LoginHistory lh:lghlist){
if (!setofuserid.contains(lh.UserId)){
mapofstatus.put(lh.UserId,lh.Status);
}
setofuserid.add(lh.UserId);
}
System.debug('Map:::'+mapofstatus);
List<Contact> listcontact=new List<Contact>();
for(User u:userlist){
Contact c=new Contact();
c.Id=u.ContactId;
c.Last_Login__c=u.LastLoginDate;
c.Last_Rest__c=u.LastPasswordChangeDate;
c.User_Login_Status__c=mapofstatus.get(u.Id);
listcontact.add(c);
}
system.debug('Contact:::'+listcontact);
update listcontact;
}
global void finish(Database.BatchableContext BC) {
}
}