Java 使用SpringBoot根据特定条件运行cron作业
我正在尝试使用SpringBoot根据特定条件运行cron作业。 例如:Java 使用SpringBoot根据特定条件运行cron作业,java,spring-boot,Java,Spring Boot,我正在尝试使用SpringBoot根据特定条件运行cron作业。 例如:if(bankName==“Sbi”)然后运行Sbi作业调度程序,if(bankName==“City”)然后运行City作业调度程序,依此类推 我通过数据库获取银行名称(通过客户帐号获取银行详细信息的服务),但我无法根据指定的条件运行作业 我期待输出,因为银行名称为“sbi”,然后运行task1作业,银行名称为“city”,然后运行task2作业。但即使不满足条件,它也会运行task3作业(银行名称为“hdfc”) 请查找
if(bankName==“Sbi”)
然后运行Sbi作业调度程序,if(bankName==“City”)
然后运行City作业调度程序,依此类推
我通过数据库获取银行名称(通过客户帐号获取银行详细信息的服务),但我无法根据指定的条件运行作业
我期待输出,因为银行名称为“sbi”,然后运行task1作业,银行名称为“city”,然后运行task2作业。但即使不满足条件,它也会运行task3作业(银行名称为“hdfc”)
请查找下面的代码片段
注意:为了调试的目的,我在SchedulingTask.java文件中设置了断点,但它似乎没有达到这个断点。请指导我如何解决这个问题
@SpringBootApplication
@EnableScheduling
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
// new SchedulingTask();
}
}
@Configuration
@EnableScheduling
public class SchedulingTask {
/* I have to get the Bankname from database for testing i am hard-coding the name*/
String [] bankName = {"Sbi","City"};
void foo(String[] bankName) {
for (String name : bankName) {
setBankName(name);
}
}
public void setBankName(String name) {
if(name.equalsIgnoreCase("sbi")) {
new Task1();
}
else if(name.equalsIgnoreCase("City")) {
new Task2();
}
else if(name.equalsIgnoreCase("Hdfc")) {
new Task3();
}
}
}
@Configuration
@EnableScheduling
public class Task1 {
@Bean
@ConditionalOnProperty(value = "Sbi", matchIfMissing = true, havingValue = "true")
public SchedulingTask1 scheduledSbiJob() {
return new SchedulingTask1();
}
}
@Configuration
@EnableScheduling
public class Task2 {
@Bean
@ConditionalOnProperty(value = "City", matchIfMissing = true, havingValue = "true")
public SchedulingTask2 scheduledCityJob() {
return new SchedulingTask2();
}
}
@Configuration
@EnableScheduling
public class Task3 {
@Bean
@ConditionalOnProperty(value = "Hdfc", matchIfMissing = true, havingValue = "true")
public SchedulingTask3 scheduledHdfcJob() {
return new SchedulingTask3();
}
}
@Component
public class SchedulingTask1 {
@Scheduled(cron="*/2 * * * * ?")
public void sbiTask() {
System.out.println("sbiTask method excuted at every 2 seconds. Current time is :: " +new Date());
}
}
@Component
public class SchedulingTask2 {
@Scheduled(cron="*/4 * * * * ?")
public void cityTask() {
System.out.println("cityTask method excuted at every 4 seconds. Current time is :: " +new Date());
}
}
@Component
public class SchedulingTask3 {
@Scheduled(cron="*/6 * * * * ?")
public void hdfcTask() {
System.out.println("hdfcTask method excuted at every 6 seconds. Current time is :: " +new Date());
}
}
no it is deferent question的可能重复我认为您应该使用@ConditionalOnExpression,但是您的条件参数将来自数据库,这使得您的解决方案很复杂,因为您需要在创建bean之前获取所有必需的参数。在我看来,一起运行所有调度程序,并使用一个标志启用/禁用它们。请提供使用@ConditionalOnExpression和启用/禁用的任何示例。非常感谢