Automate MinIO Image Cleanup with Spring Boot Scheduled Tasks and Cron
This guide explains how to use MinIO SDK in a Spring Boot application to schedule automatic deletion of outdated image folders, covering dependency setup, delete methods, performance considerations, cron expression configuration, thread‑pool tuning, asynchronous execution, and extensible configuration via properties.
Introduction
In project development we use MinIO as an image storage service. Over time many historical images become unnecessary, so a scheduled cleanup is needed to delete files older than a specified date.
Dependencies
Core dependencies: MinIO client and Spring Boot starter (which already includes scheduling support).
<!-- Maven dependency snippet -->Delete Methods
Utility class MinioUtil provides methods: deleteDateFoldersBefore(LocalDate endExclusive): deletes all date‑based directories before the given date. deleteSingleFolder(String prefix): deletes all objects under a single prefix.
File naming follows the pattern /bucketName/yyyy-MM-dd/uuid.extension.
Implementation Details
Methods use MinIO's listObjects with lazy pagination and removeObjects to batch delete. Idempotency is ensured by ignoring already deleted objects.
Cron Expression Configuration
Spring's @Scheduled(cron = "...") supports 6‑field cron expressions. Examples include:
Every minute: 0 * * * * ? Every day at 1 AM: 0 0 1 * * ? First day of each month at 3 AM:
0 0 3 1 * ?Thread‑Pool Scheduler
Multiple scheduled tasks share a single thread by default. Configuring a ThreadPoolTaskScheduler improves isolation and parallelism.
<!-- SchedulerConfiguration class snippet -->Asynchronous Execution
Long‑running tasks should run asynchronously to avoid blocking the scheduler. Define a ThreadPoolTaskExecutor and annotate the task method with @Async.
<!-- AsyncConfiguration class snippet -->Extending the Solution
Properties can be externalized to control enable flag, retain days, earliest date, and cron expression. The utility class reads these values at startup, and the scheduled task uses them to compute the cutoff date.
Testing
A JUnit test invokes minioUtil.deleteDateFoldersBefore with a custom date to verify the cleanup logic.
Additional Resources
Online cron validators such as crontab.guru are recommended for testing expressions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
