首页 > 解决方案 > 如何在 Spring 中运行 Cron 作业

问题描述

我在 spring 中创建了一个类 ApplicationDataScheduler,它有一个带有 @Scheduled 注释的方法 reportGenerator。此方法以 excel 的形式生成报告,其中包含来自表格的数据。因此,类 ApplicationDataScheduler 和方法 reportGenerator,它们都在 intelliJ 中显示为浅灰色,表示从不使用类和从不使用方法。我需要在某处申报或打电话给他们吗?以下是代码:

    @Component 
public class ApplicationDataScheduler { 
@Autowired 
HibernateUtils hibernateUtils; 
 
@Scheduled(cron = "0 0 0 * * *") 
public void reportGenerator() throws IOException { 
List<Application> applications = hibernateUtils.getAllEntities(Application.class); 
XSSFWorkbook exportedData = convertToExcel(applications); 
FileOutputStream output = new FileOutputStream(new File("Applications.xlsx")); 
exportedData.write(output); 
output.close(); 
} 
 
private XSSFWorkbook convertToExcel(List<Application> applications) { 
XSSFWorkbook workbook = new XSSFWorkbook(); 
XSSFSheet sheet = workbook.createSheet("applications_data"); 
int row_index = 0; 
for (Application app : applications) { 
XSSFRow row = sheet.createRow(row_index++); 
fill_row(app, row); 
} 
return workbook; 
} 
 
private void fill_row(Application app, XSSFRow row) { 
XSSFCell cell = row.createCell(0); 
cell.setCellValue(app.getApplicationId()); 
 
cell = row.createCell(1); 
cell.setCellValue(app.getAppCode()); 
 
cell = row.createCell(2); 
cell.setCellValue(app.getApplicationSubmittedDate()); 
 
cell = row.createCell(3); 
cell.setCellValue(app.getRemarks()); 
 
cell = row.createCell(4); 
cell.setCellValue(app.getCreatedByUser()); 
 
cell = row.createCell(5); 
cell.setCellValue(app.getUpdatedByUser()); 
} 
} 

标签: javaspring

解决方案


首先,检查它确实没有运行,因为一切看起来都很好。例如,您可以在计划任务中放置logger.info某个位置,然后运行您的应用程序。关于 IntelliJ 没有突出显示您的方法,这完全没问题,因为您自己的代码内部没有任何东西运行它,它是从 spring 框架中调用的。


推荐阅读