我正在按照本指南在Spring Boot中开始计划任务 https://spring.io/guides/gs/scheduling-tasks/。
我想为同一类中的不同任务添加更多方法,想知道是否可以通过属性在@ConditionalOnProperty
上启用/禁用方法级别的任务,看来@ConditionalOnProperty
在仅限于类级别,而不是方法级别(按照下面的代码示例,这不起作用)。还有其他方法吗?还是必须创建另一个包含任务二的类才能分别禁用/启用它们?
@Component
public class SchedulingTasks {
private static final Logger log = LoggerFactory.getLogger(SchedulingTasks.class);
@Scheduled(fixedRate = 50000)
public void jobOne() {
log.info("job one started at {}", LocalDateTime.now());
}
@Scheduled(fixedRate = 50000)
@ConditionalOnProperty(name="job.two", havingValue="true")
public void jobTwo() {
log.info("just two started at {}", LocalDateTime.now());
}
}
答案 0 :(得分:0)
您可以将@ConditionalOnProperty
应用于方法和类型,但这似乎仅适用于注册Bean的方法(请参见@Conditional
文档)。
您应该创建单独的Bean,可以在其中控制@ConditionalOnProperty的注册,然后将@Scheduled
注释应用于Bean中的方法。
示例:
@Slf4j
@Service
@ConditionalOnProperty(prefix = "schedule", name = {"job.one"}, havingValue = "true")
public class JobOneScheduler {
@Scheduled(cron = "*/2 * * * * *")
public void runJob() {
log.debug( "Running job one... {}", LocalDateTime.now() );
}
}
@Slf4j
@Service
@ConditionalOnProperty(prefix = "schedule", name = {"job.two"}, havingValue = "true")
public class JobTwoScheduler {
@Scheduled(cron = "*/5 * * * * *")
public void runJob() {
log.debug( "Running job two... {}", LocalDateTime.now() );
}
}
application.properties:
schedule.job.one=true
schedule.job.two=false