Codion provides a few classes with miscellanous utility functions.
2. TaskScheduler
TaskScheduler provides a simple, lightweight way to execute tasks periodically on a background thread.
2.1. Basic Usage
Create a scheduler that runs a task at fixed intervals:
// Build a scheduler that runs a task every 5 seconds
TaskScheduler scheduler =
TaskScheduler.builder()
.task(() -> System.out.println("Running scheduled task"))
.interval(5, TimeUnit.SECONDS)
.initialDelay(10) // Wait 10 seconds before first execution
.name("My Task Scheduler") // Name for debugging
.build();
// Start the scheduler
scheduler.start();
// Check if it's running
boolean running = scheduler.running();
// Stop the scheduler when done
scheduler.stop();
2.2. Auto-Start
Use the start() method to build and start the scheduler in one step:
// Build and start in one step
TaskScheduler scheduler =
TaskScheduler.builder()
.task(this::performMaintenance)
.interval(30, TimeUnit.SECONDS)
.name("Maintenance Task")
.start(); // Builds and starts immediately
2.3. Thread Naming
The name() method sets the thread name, which is useful for debugging and thread dumps:
TaskScheduler scheduler =
TaskScheduler.builder()
.task(maintenanceTask)
.interval(30, TimeUnit.SECONDS)
.name("Connection Maintenance") // Appears in thread dumps
.start();
|
Tip
|
Always name your scheduler threads descriptively to make debugging easier. |
2.4. Custom ThreadFactory
For advanced control over thread creation, provide a custom ThreadFactory:
// Use a custom ThreadFactory for advanced control
TaskScheduler scheduler =
TaskScheduler.builder()
.task(() -> System.out.println("Custom thread task"))
.interval(1, TimeUnit.MINUTES)
.threadFactory(runnable -> {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
thread.setPriority(Thread.MIN_PRIORITY);
thread.setName("Custom Task Thread");
return thread;
})
.start();
|
Note
|
When using a custom threadFactory(), the name() setting is ignored since the ThreadFactory has full control over thread creation.
|
2.5. Common Use Cases
TaskScheduler is ideal for:
-
Connection maintenance - Periodically cleaning up idle connections
-
Cache cleanup - Removing stale cache entries
-
Statistics collection - Gathering metrics at regular intervals
-
Health checks - Monitoring system health
-
Periodic saves - Auto-saving user preferences or state
All scheduler threads are daemon threads by default, so they won’t prevent JVM shutdown.