java - 使用java的定时器任务
问题描述
我有一个要求,在一段时间内(假设是 50 秒,时间可能是动态的)我必须从服务器获取一些数据。同时每 10 秒(在这 30 秒之间),我必须向服务器发送一些密钥。
对于那个 iam 使用下面的代码....但它不工作
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long duration = (50 * 1000);
do {
// RESEt request call code goes here..
/////
//////
System.out.println("Rest request");
java.util.Timer t = new java.util.Timer();
java.util.TimerTask task = new java.util.TimerTask() {
@Override
public void run() {
//Sending key every 10 sec
RemoteKey.send(PageUp);
}
};
t.schedule(task, 0, (10 * 1000));
// This do while loop will execute 50 sec
} while ((System.currentTimeMillis() - startTime) < duration);
}
解决方案
这将是最佳方法,使用现代ScheduledExecutor
因为时间跨度,比如 50 秒,由获取操作决定,并且该操作是同步的,您只需要等待它结束。
// Start the executor, scheduling your Runnable Task to run every 10 seconds
executorService.scheduleAtFixedRate(
() -> {
// Send your data
}, 0, 10, TimeUnit.SECONDS);
// Fetch data from your Server.
// That's a blocking operation, which, let's say will take 50 seconds
// Stop the Executor as the time is over
executorService.shutdown();
Executor
可以通过工厂方法创建。
Executors.newScheduledThreadPool(5); // For multiple, concurrent threads
Executors.newSingleThreadScheduledExecutor(); // For a synchronous "queue"
推荐阅读
- android - 如何在 FirestoreRecyclerAdapter 中添加 2 个不同的查询?
- javascript - 单击一个按钮会折叠所有 div 而不是它所属的 div
- php - Laravel 5.6 - 雄辩的多对多错误1066
- swift - 是否可以让枚举类型将它们存储在 Swift 4 的集合中?
- javascript - html复选框取消单击隐藏函数变量
- react-native - 如何在 React Native Text 元素的文本中放置颜色?
- django - 在Django的另一个for循环中循环for循环
- javascript - ember.js 如何插入新记录?
- azure - 如何在 azure applications 洞察力中执行不同的声明?
- sql - 使用 shell 脚本创建了一个数据库,但是不允许用户登录