@Scheduled如何配置开关启用
时间: 2023-11-08 15:06:07 浏览: 59
自定义@Configuration配置类启用开关.zip
可以通过在方法上添加@Conditional注解来实现@Scheduled的开关启用。具体实现方式如下:
1. 定义一个配置类,用于控制@Scheduled的开关状态:
```
@Configuration
public class ScheduleConfig {
@Value("${schedule.enabled}")
private boolean enabled;
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(10);
scheduler.setThreadNamePrefix("scheduled-task-");
scheduler.setWaitForTasksToCompleteOnShutdown(true);
scheduler.setAwaitTerminationSeconds(30);
scheduler.setErrorHandler(new ScheduledTaskErrorHandler());
if (enabled) {
scheduler.initialize();
}
return scheduler;
}
}
```
2. 在方法上添加@Scheduled注解,并在@Conditional注解中指定条件:
```
@Component
public class MyScheduledTask {
@Scheduled(cron = "0 0/5 * * * ?")
@Conditional(ScheduleEnabledCondition.class)
public void doSomething() {
// do something
}
}
public class ScheduleEnabledCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
return environment.getProperty("schedule.enabled", Boolean.class, false);
}
}
```
3. 在配置文件中配置@Scheduled的开关状态:
```
schedule.enabled=true
```
阅读全文