I have a little problem. We have 2000 records of type "Immobenutzer". So now I am facing the problem of governor limits. I need to log the logintimes for each user. So for each user there has to be a new query to get the amount of login times. Now I have no clue how to avoid these limits anymore. I just know about the trick I used in the first execute method, by using not a for loop and then querying inside, but using the query as statement for both lists and single record. Can someone help?
global class RealtyUserLoginDays implements Schedulable
{
// Execute method
global void execute(SchedulableContext SC)
{
for(List<Realty_User__c> userList:[SELECT Id, CreatedDate, Tage_ohne_Login__c, Tage_mit_aufeinander_folgendem_Login__c FROM Realty_User__c WHERE Active__c = TRUE])
{
for(Realty_User__c user:userList)
{
Integer consecutiveLogins = getConsecutiveLogins(user.Id);
if(consecutiveLogins > 0)
{
user.Tage_mit_aufeinander_folgendem_Login__c = consecutiveLogins;
user.Tage_ohne_Login__c = 0;
}
else
{
Integer daysWithoutLogin = getDaysWithoutLogin(user.Id, user.CreatedDate.date());
user.Tage_ohne_Login__c = daysWithoutLogin;
user.Tage_mit_aufeinander_folgendem_Login__c = 0;
}
}
if(userList.size() > 0)
{
update userList;
}
}
}
public static Integer getConsecutiveLogins(Id userId)
{
Set<Date> loginTimes = new Set<Date>();
for (Loginzeiten_Maklerportal__c login : [SELECT Loginzeit__c FROM Loginzeiten_Maklerportal__c WHERE Immo_Benutzer__c = :userId])
{
loginTimes.add(login.Loginzeit__c.date());
}
Integer consecutiveLogins = 0;
while (loginTimes.contains(Date.today().addDays(-consecutiveLogins)))
{
consecutiveLogins++;
}
return consecutiveLogins;
}
public static Integer getDaysWithoutLogin(Id userId, Date createdDate)
{
Date today = Date.today();
try
{
Loginzeiten_Maklerportal__c login = [SELECT Loginzeit__c FROM Loginzeiten_Maklerportal__c WHERE Immo_Benutzer__c = :userId ORDER BY Loginzeit__c DESC LIMIT 1];
Date loginZeit = login.Loginzeit__c.date();
Integer daysWithoutLogin = loginZeit.daysBetween(today);
return daysWithoutLogin;
}
catch(Exception e)
{
Integer daysWithoutLogin = createdDate.daysBetween(today);
return daysWithoutLogin;
}
}
}