当前位置:首页 > Java 框架原理百科 > 正文

Java优学网SpringBoot定时任务教程:轻松掌握自动化调度与分布式锁实战

@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优学网SpringBoot定时任务教程:轻松掌握自动化调度与分布式锁实战

你可能想看:

相关文章:

文章已关闭评论!