Async Tasks & Scheduling
Spring Boot makes it trivial to run tasks asynchronously in a thread pool or schedule them on a cron-like schedule — without requiring external message queues for simple use cases.
1 @Async — Non-Blocking Execution
Java — Async Configuration & Usage
// Enable async support in your main app class or config
@SpringBootApplication
@EnableAsync
public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }
// Configure thread pool
@Configuration
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("async-task-");
executor.initialize();
return executor;
}
}
// Mark methods as async
@Service
public class EmailService {
@Async // Runs in a separate thread
public CompletableFuture<Void> sendWelcomeEmail(String to, String name) {
// Simulate slow email sending
Thread.sleep(2000);
System.out.println("Email sent to " + to);
return CompletableFuture.completedFuture(null);
}
}
// Controller doesn't wait for email
@PostMapping
public ResponseEntity<UserDto> create(@RequestBody @Valid CreateUserRequest req) {
UserDto user = userService.create(req);
emailService.sendWelcomeEmail(user.getEmail(), user.getName()); // Fire and forget
return ResponseEntity.status(201).body(user);
}
2 @Scheduled — Cron Jobs
Java — Scheduled Tasks
@Component
@EnableScheduling
public class ScheduledTasks {
// Fixed delay: 5 seconds AFTER last execution completes
@Scheduled(fixedDelay = 5000)
public void cleanupExpiredTokens() {
tokenRepository.deleteByExpiryBefore(Instant.now());
log.info("Expired tokens cleaned up");
}
// Fixed rate: every 60 seconds regardless of completion
@Scheduled(fixedRate = 60000)
public void syncExternalData() {
externalApiService.syncProducts();
}
// Cron expression: every day at 2:00 AM
@Scheduled(cron = "0 0 2 * * *")
public void generateDailyReport() {
reportService.generateAndEmail();
}
// Cron: every Monday at 9:00 AM (with timezone)
@Scheduled(cron = "0 0 9 * * MON", zone = "Asia/Kolkata")
public void weeklyNewsletter() {
newsletterService.sendToAllSubscribers();
}
}
3 Code Challenge
Challenge: Create a report generation service that runs every night at midnight (using
@Scheduled), generates a sales summary CSV asynchronously (using @Async for the heavy computation), and emails it to admins when complete using CompletableFuture.thenRun().