计划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接口。

基本上,它允许您调用一个schedule方法并传递一个Runnable和一个Date参数。

在这种情况下,您的调用需要实现Runnable,并以Date格式参数化动态执行周期。假设您有一个名为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与字段连接起来,并提供您想要传递的日期

编辑:此接口还为您提供了可以传递时间跨度(固定或延迟(的方法。

最新更新