目前遇到的问题:
我们可以在springboot中使用@scheduled注解来完成定时任务。我现在有两台机器部署同一个应用。
一台希望开启这个定时器,另一台希望关闭它。
解决方案:
1.
自己定义一个参数,在定时方法中对其判断。由于我这个方法每分钟执行一次。所以效率不高。
application.properties :
scheduling.enabled=true
业务代码:
@Value("${scheduling.enabled}")
private boolean taskSwitch;
@scheduled
public void task(){
if(!taskSwitch){
return;
}
//do anything
}
2.
可以通过配置文件的方式来决定这个定时器的开关状态,能从源头上停掉这个定时器。
把定时任务独立一个Scheduler.java出来,对这个类加载进行控制,继而解决问题:
application.properties :
scheduling.enabled=true
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class Scheduler {
@Scheduled(cron = "0 */1 * * * ?")
private void yourTask() {
}
}