callingmahendra / springboot3-sample

Springboot sample Repo
Apache License 2.0
0 stars 0 forks source link

Add a logic to delete todo after 3 days of creation #4

Open callingmahendra opened 3 months ago

callingmahendra commented 3 months ago

write a cron job to delete todo after 3 day of creation using springbok

callingmahendra commented 2 months ago

Implement a scheduled task in your Spring Boot application using the @Scheduled annotation. Inject the TodoRepository and use a query to find and delete TODOs older than 3 days.

import org.springframework.scheduling.annotation.Scheduled;

@Service
public class TodoService {

    // ... other methods ...

    @Scheduled(cron = "0 0 0 * * *") // Runs daily at midnight
    public void deleteOldTodos() {
        LocalDate threeDaysAgo = LocalDate.now().minusDays(3);
        todoRepository.deleteByCreatedAtBefore(threeDaysAgo);
    }
}

Explanation:

  1. *`@Scheduled(cron = "0 0 0 ")`**: This configures the method to run daily at midnight. You can adjust the cron expression for different schedules.
  2. LocalDate.now().minusDays(3): This calculates the date three days before the current date.
  3. todoRepository.deleteByCreatedAtBefore(threeDaysAgo): This assumes you add a createdAt field (with appropriate mapping) to your Todo entity. This line will delete all TODOs created before the calculated date.

Remember: