@SpringBootApplication @EnableScheduling public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Component public class ReportTask {
// 每天凌晨1点执行
@Scheduled(cron = "0 0 1 * * ?")
public void generateDailyReport() {
// 生成日报逻辑
}
// 每30分钟执行一次
@Scheduled(fixedRate = 1800000)
public void refreshCache() {
// 刷新缓存逻辑
}
}
@Configuration @EnableScheduling public class SchedulerConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(10);
scheduler.setThreadNamePrefix("scheduled-task-");
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
return scheduler;
}
}
@Component public class DistributedScheduledTask {
@Scheduled(cron = "0 */5 * * * *")
public void distributedDataSync() {
String lockKey = "task:data-sync:lock";
String requestId = UUID.randomUUID().toString();
try {
boolean locked = redisTemplate.opsForValue()
.setIfAbsent(lockKey, requestId, Duration.ofMinutes(4));
if (locked) {
// 获取锁成功,执行任务逻辑
executeDataSync();
}
} finally {
// 只释放自己加的锁
if (requestId.equals(redisTemplate.opsForValue().get(lockKey))) {
redisTemplate.delete(lockKey);
}
}
}
}
@SpringBootApplication @EnableScheduling public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Component public class SalesReportGenerator {
@Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行
public void generateDailyReport() {
LocalDate reportDate = LocalDate.now().minusDays(1);
// 分步骤统计,避免单次查询数据量过大
SalesSummary summary = new SalesSummary();
summary.setTotalOrders(countOrders(reportDate));
summary.setTotalRevenue(calculateRevenue(reportDate));
summary.setTopProducts(findTopProducts(reportDate));
summary.setUserStatistics(analyzeUserBehavior(reportDate));
// 生成Excel报表
String reportPath = excelService.generateReport(summary);
// 发送邮件通知
emailService.sendReportToManagers(reportPath, reportDate);
logger.info("每日销售报表生成完成: {}", reportDate);
}
private long countOrders(LocalDate date) {
// 使用数据库的count函数,避免加载全部数据
return orderRepository.countByOrderDate(date);
}
}

你可能想看:
Java优学网MyBatis查询教程:从基础到企业级实战,轻松掌握高效查询技巧
Java优学网SpringBoot过滤器教程:轻松掌握Web应用安全与性能优化
Java优学网while循环教程:从基础语法到实战应用,轻松掌握循环编程
Java优学网MySQL数据类型教程:从基础到实战,轻松掌握数据库设计核心技巧
Java优学网SpringBoot自定义配置教程:轻松掌握个性化配置技巧,告别繁琐开发
Java优学网Spring AOP代理教程:轻松掌握Spring AOP核心原理与实战技巧,告别重复代码烦恼