我正在尝试一些代码来实现计划任务,并提出了这些代码.
import java.util.*;
class Task extends TimerTask {
int count = 1;
// run is a abstract method that defines task performed at scheduled time.
public void run() {
System.out.println(count+" : Mahendra Singh");
count++;
}
}
class TaskScheduling {
public static void main(String[] args) {
Timer timer = new Timer();
// Schedule to run after every 3 second(3000 millisecond)
timer.schedule( new Task(), 3000);
}
}
Run Code Online (Sandbox Code Playgroud)
我的输出:
1 : Mahendra Singh
Run Code Online (Sandbox Code Playgroud)
我期望编译器以3秒的周期间隔打印一系列Mahendra Singh,但是尽管等了大约15分钟,我只得到一个输出......我该如何解决这个问题?
我需要暂停一个while循环一段特定的毫秒数.我尝试过使用Thread.sleep(持续时间),但它不准确,特别是在循环方案中.毫秒精度在我的程序中很重要.
这是算法,我不想回去检查条件,直到expectedElapsedTime过去.
while (condition) {
time = System.currentTimeMillis();
//do something
if (elapsedTime(time) < expectedElapsedTime) ) {
pause the loop // NEED SUBSTITUTE FOR Thread.sleep()
}
// Alternative that I have tried but not giving good results is
while ((elapsedTime(time) < expectedElapsedTime)) {
//do nothing
}
}
long elapsedTime(long time) {
long diff = System.currentTimeMillis() - time;
return diff;
}
Run Code Online (Sandbox Code Playgroud)