60 lines
2.1 KiB
Java
60 lines
2.1 KiB
Java
package com.krylov.refound.service;
|
|
|
|
import com.krylov.refound.entity.Post;
|
|
import com.krylov.refound.enums.PostStatus;
|
|
import com.krylov.refound.repository.FavoriteRepository;
|
|
import com.krylov.refound.repository.PostRepository;
|
|
import java.time.LocalDateTime;
|
|
import java.util.List;
|
|
import lombok.RequiredArgsConstructor;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.scheduling.annotation.Scheduled;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
|
|
@Slf4j
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class SchedulerService {
|
|
|
|
private final PostRepository postRepository;
|
|
private final FavoriteRepository favoriteRepository;
|
|
|
|
/**
|
|
* Runs every day at 00:01 to delete:
|
|
* 1. Posts with CLOSED status
|
|
* 2. Posts older than 6 months
|
|
*/
|
|
@Scheduled(cron = "0 1 0 * * ?")
|
|
@Transactional
|
|
public void deleteExpiredPosts() {
|
|
log.info("Starting scheduled cleanup of expired posts...");
|
|
|
|
LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
|
|
|
|
// Find and delete posts with CLOSED status
|
|
List<Post> closedPosts = postRepository.findByStatus(PostStatus.CLOSED);
|
|
if (!closedPosts.isEmpty()) {
|
|
// Delete favorites first to avoid foreign key constraint violation
|
|
favoriteRepository.deleteByPostIn(closedPosts);
|
|
log.info("Deleted {} favorites for CLOSED posts", closedPosts.size());
|
|
|
|
postRepository.deleteAll(closedPosts);
|
|
log.info("Deleted {} posts with CLOSED status", closedPosts.size());
|
|
}
|
|
|
|
// Find and delete posts older than 6 months
|
|
List<Post> oldPosts = postRepository.findByCreatedAtBefore(sixMonthsAgo);
|
|
if (!oldPosts.isEmpty()) {
|
|
// Delete favorites first to avoid foreign key constraint violation
|
|
favoriteRepository.deleteByPostIn(oldPosts);
|
|
log.info("Deleted {} favorites for old posts", oldPosts.size());
|
|
|
|
postRepository.deleteAll(oldPosts);
|
|
log.info("Deleted {} posts older than 6 months", oldPosts.size());
|
|
}
|
|
|
|
log.info("Scheduled cleanup completed successfully");
|
|
}
|
|
}
|