[英]API call every day at a specific time in java?
我想在 java 中創建一個調度程序,它每天在特定時間調用 API 並將內容保存在文本文件中。 一種選擇是做這樣的事情。 https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/ 。 但是在 Java 中還有其他方法可以做到這一點嗎? 我正在尋找最有效的方法。 有什么建議么。
@Component
class WelcomeService {
public String retrieveWelcomeMessage() {
//Complex Method
String msgType="Hello World";
RestTemplate restTemplate = new RestTemplate();
String consumeJSONString = restTemplate.getForObject("https://ubasocials.ubagroup.com/geo-locationservice/odata/ATMs", String.class);
writetexttofile(consumeJSONString);
/* Gson gson = new GsonBuilder().create();
Quote r = gson.fromJson(consumeJSONString, Quote.class);
msgType=r.getValue().getQuote();*/
return msgType;
}
}
使用Spring boot: 1.在如下所示的主要類中添加@EnableScheduling注解
@SpringBootApplication
@EnableScheduling
public class MySchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(MySchedulerApplication .class, args);
}
}
@Component
public class JobScheduler {
@Scheduled(cron = "*/1 * * * * ?")
public void cronJobSch() {
//to do
}
}```
使您的 WelcomeService 可運行,然后將其傳遞給 ScheduledExecutorService 的實例。
private final ScheduledExecutorService sheduledExecutorService = Executors.newScheduledThreadPool(1);
sheduledExecutorService.scheduleAtFixedRate(runnableWelcomeService, 0, 1, TimeUnit.DAYS);
如果您不想使用任何框架,例如 spring。 您可以使用Windows 任務計划程序來安排您的 Java 代碼。
第 1 步:將您的 java 代碼打包為可運行的 jar。
第 2 步:創建一個運行 jar 的批處理文件。
第三步:在windows tash scheduler中使用批處理文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.