4
4
import lombok .RequiredArgsConstructor ;
5
5
import lombok .extern .slf4j .Slf4j ;
6
6
import org .springframework .beans .factory .annotation .Value ;
7
+ import org .springframework .data .domain .Page ;
7
8
import org .springframework .data .domain .PageRequest ;
8
9
import org .springframework .scheduling .annotation .Scheduled ;
9
10
import org .springframework .stereotype .Service ;
10
11
11
12
import java .time .LocalDateTime ;
12
- import java .util .List ;
13
13
14
14
import static fr .dossierfacile .scheduler .tasks .TaskName .TENANT_DELETION ;
15
+ import static java .time .LocalDateTime .*;
15
16
16
17
@ Slf4j
17
18
@ Service
18
19
@ RequiredArgsConstructor
19
20
public class TenantDeletionTask {
20
21
22
+ private static final int PAGE_SIZE = 1000 ;
23
+
21
24
@ Value ("${months_for_deletion_of_archived_tenants:12}" )
22
25
private Integer monthsForDeletionOfTenants ;
23
26
private final TenantRepository tenantRepository ;
@@ -26,16 +29,27 @@ public class TenantDeletionTask {
26
29
@ Scheduled (cron = "${cron.account-deletion}" )
27
30
private void deleteOldAccounts () {
28
31
LoggingContext .startTask (TENANT_DELETION );
29
- List <Long > tenantIdsToDelete = getTenantsToDelete ();
30
- tenantIdsToDelete .forEach (this ::deleteTenant );
31
- log .info ("Deleted {} inactive old tenants" , tenantIdsToDelete .size ());
32
+
33
+ LocalDateTime limitDate = now ().minusMonths (monthsForDeletionOfTenants );
34
+ deleteTenantsNotActiveSince (limitDate );
35
+
32
36
LoggingContext .endTask ();
33
37
}
34
38
35
- private List <Long > getTenantsToDelete () {
36
- LocalDateTime limitDate = LocalDateTime .now ().minusMonths (monthsForDeletionOfTenants );
37
- PageRequest pageRequest = PageRequest .of (0 , 5000 );
38
- return tenantRepository .findByLastUpdateDate (limitDate , pageRequest );
39
+ private void deleteTenantsNotActiveSince (LocalDateTime limitDate ) {
40
+ Page <Long > toDelete = tenantRepository .findByLastUpdateDate (limitDate , PageRequest .of (0 , PAGE_SIZE ));
41
+ log .info ("Found {} inactive tenants to delete ({} months old)" , toDelete .getTotalElements (), monthsForDeletionOfTenants );
42
+
43
+ deleteAllTenants (toDelete );
44
+
45
+ while (toDelete .hasNext ()) {
46
+ toDelete = tenantRepository .findByLastUpdateDate (limitDate , toDelete .nextPageable ());
47
+ deleteAllTenants (toDelete );
48
+ }
49
+ }
50
+
51
+ private void deleteAllTenants (Page <Long > tenantIds ) {
52
+ tenantIds .forEach (this ::deleteTenant );
39
53
}
40
54
41
55
private void deleteTenant (Long tenantId ) {
0 commit comments