java - 如何在 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());
}
}
解决方案
首先,检查它确实没有运行,因为一切看起来都很好。例如,您可以在计划任务中放置logger.info
某个位置,然后运行您的应用程序。关于 IntelliJ 没有突出显示您的方法,这完全没问题,因为您自己的代码内部没有任何东西运行它,它是从 spring 框架中调用的。
推荐阅读
- c# - C++ 中的“笛卡尔积”方法
- c++builder - 如何在 Rad Studio (C++ Builder) 10.3 中更改编译器
- json - Golang 解组数组给出运行时错误:索引超出范围
- r - 根据 r 中的条件,用一组新的观察值替换特定的观察值
- sas - 如何将一个表的值作为 SAS Base 中另一个表的名称?
- angular - 在 FE 中使用 BE 提供的 Enum 是可能的,如何?
- sql - 找一个吃过苹果没吃过香蕉的人
- javascript - 在多轨设置中使用waveform.js 库在音频中寻找位置的问题
- python - pyqt在读取文件时没有响应
- html-email - 在 macOS/OSX 上查看 Mutt 邮件中的内联图像