java - 安排 Cronjob 更改运行时 - JAVA
问题描述
我需要传递值运行时间,并且根据值我需要更改 cronjob 执行间隔,但是当我使用 @Scheduled() 时我不能这样做,因为它需要常量。我该怎么做或是否有其他方法?我也无法将 env.getProperty 值分配给本地方法之外的变量。
String cronValue=env.getProperty("cron");
@Override
@Scheduled(cron = "0 0 0 * * *", zone = "Asia/Colombo")
public void createFile() throws IOException {
String location=env.getProperty("location");
LocalDate today = LocalDate.now( ZoneId.of( "Asia/Colombo" ) );
String date = today.toString();
String source=location+"report-temp.csv";
String dailyFile=location+"report-"+date+".csv";
// File (or directory) with old name
File oldFile = new File("/home/lkr/nish/report-temp.csv");
File newFile = new File(dailyFile);
//if(file2.exists()) throw new java.io.IOException("file exists");
boolean success = oldFile.renameTo(newFile);
if (!success) {
// File was not successfully renamed
}
System.out.println("Daily File Created!");
}
解决方案
嗯,您可以尝试使用TaskScheduler Spring 接口。
基本上,它允许您调用调度方法并传递Runnable和Date参数。
在这种情况下,您的调用需要实现 Runnable 并以日期格式参数化您的动态执行周期。假设您有一个名为 FileGenerator 的类,并且它实现了 Runnable。它还必须实现 Runnable 接口的方法,因此您必须有一个名为 run(); 的方法;
class FileGenerator implements Runnable {
TaskScheduler scheduler;
Date parametrizedDate;
@Override
public void run() {
scheduler.schedule(this::createFile, parametrizedDate);
}
private void createFile() {
String location=env.getProperty("location");
LocalDate today = LocalDate.now( ZoneId.of( "Asia/Colombo" ) );
String date = today.toString();
String source=location+"report-temp.csv";
String dailyFile=location+"report-"+date+".csv";
// File (or directory) with old name
File oldFile = new File("/home/lkr/nish/report-temp.csv");
File newFile = new File(dailyFile);
//if(file2.exists()) throw new java.io.IOException("file exists");
boolean success = oldFile.renameTo(newFile);
if (!success) {
// File was not successfully renamed
}
System.out.println("Daily File Created!");
}
由于 TaskScheduler 本身就是一个接口,因此您必须配置它的一个实现,最好是在一个 bean 中。使用 ThreadPoolTaskScheduler 的一种可能性:
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
剩下要做的就是用字段自动装配 bean 并提供您想要传递的日期。
编辑:此界面还为您提供了可以传递时间跨度(固定或延迟)的方法。更多关于它的信息在这里
推荐阅读
- r - 如何使用 dplyr 获得相同的分组结果以获得与 sqldf 结果一致的结果?
- python - 没有名为“signxml”的模块
- reactjs - Recharts Js如何始终从响应容器底部渲染区域图
- r - R中的ggplot2包问题,如何设置颜色和图例
- django - 在 Django 连接中使用指定的数据库
- ios - 完成播放视频后,锁屏小部件不会消失
- sap-cloud-sdk - 尽管使用了解决方法,但租户不可用异常
- wordpress - 自定义帖子类型模板中的 Elementor 自定义过滤器查询 - 如何查询要过滤的字段值?
- django - 有帖子的用户应该只能在正确的代码下面编辑博客,但这是专业的方法吗
- cmake - CMake ExternalProject_Add 并行构建问题