我正在尝试以固定的速率从spring-boot安排服务,但会出现初始延迟,
部署后,我期望read方法应该在5秒后每10秒执行一次,但是控制台中什么也不显示。
这是我的主要应用程序类
@SpringBootApplication
@EnableScheduling
public class ArgusAPIApplication {
@Value("${proxy.host}")
private String proxyHost;
@Value(("${proxy.port}"))
private int proxyPort;
@Value(("${readTimeout}"))
private int readTimeout;
@Value(("${connectTimeout}"))
private int connectTimeout;
public static void main(String[] args) {
SpringApplication.run(ArgusAPIApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy= new Proxy(Type.HTTP, new InetSocketAddress(proxyHost,proxyPort));
requestFactory.setProxy(proxy);
requestFactory.setReadTimeout(readTimeout);
requestFactory.setConnectTimeout(connectTimeout);
return new RestTemplate(requestFactory);
}
}
我希望以固定的时间间隔安排服务 下面给出了带有@Scheduled注释的服务类的服务类
@Service
public class targusTractoscalingScheduler {
private static final Logger logger = LogManager.getLogger(targusTractoscalingScheduler.class);
@Autowired
targusController targusController;
@Autowired RestTemplate restTemplate;
private boolean firstTime = true;
@Value("aaaaaaaaaaaaaaaa")
private String apiKey;
@Value("xxxxxxxxxxxxxxxxxxxxxxx")
private String applicationKey;
@Value("${ddUrl}")
private String ddUrl;
@Value("/filter/instance")
private String ddInstanceApiPath;
@Value("/stop/job/{Tractoscalinggroup}")
private String ddStopJobPath;
/**
* Scheduler method that will run at every predefined interval.
*/
@Scheduled(initialDelayString = "5000", fixedRateString = "10000")
public void targusAsgAndCmdbASgCompare() {
List<targusData> targusDatas = targusController.gettargusData();
if (CollectionUtils.isEmpty(targusDatas)) {
logger.debug("Empty list obtained from targus, so simply exiting from method");
return;
}
processtargusData(targusDatas);
firstTime = false;
}
但是服务没有触发,springboot文件也提供了类似的实现。
答案 0 :(得分:1)
这里是一个例子:
@EnableScheduling
@SpringBootApplication
public class MyExampleCronApplication {
public static void main(String[] args) {
SpringApplication.run(MyExampleCronApplication.class, args);
}
@Scheduled(initialDelay=5000,fixedRate=10000)
public void test() {
System.out.println(Date.from(Instant.now()).getSeconds());
}
}
输出:
注意:我通过将计划的方法放入服务中来分离代码,并且可以正常工作。