尝试将函数循环一段特定的时间,请记住该函数大约需要20秒才能完成执行。
显然可以选择使用以下内容:
long startTime = System.currentTimeMillis();
long length = 30000;
while(System.currentTimeMillis() - startTime <= length){
foo(); // takes 20 seconds to finish executing
}
唯一的缺点就是,如果foo需要20秒才能运行,此代码将不会在30中断,并且在错误之前将循环另外20秒,因此执行40秒。
foo就是这段代码:
new SequenceStrategy(NUMBER_FAIRY_LIGHTS, colours).runLightsAlgorithm();
public class SequenceStrategy implements LightsStrategy {
private List<Light> fairyLightsList = new ArrayList<>();
public SequenceStrategy(int numFairyLights, String[] colours) {
for (int i = 0; i < numFairyLights; i += colours.length) {
for (int j = 0; j < colours.length && i + j < numFairyLights; j++) {
fairyLightsList.add(new Light(colours[j], OFF_STATUS, i + j));
}
}
}
public void runLightsAlgorithm() {
for (int i = 0; i < fairyLightsList.size(); i++) {
lightUtilsObject.outputLightMessage(fairyLightsList.get(i).getLightIndex() + 1, fairyLightsList.get(i).getLightColour(), ON_STATUS);
//Thread sleep for 0.5 second after toggling light in sequence
lightUtilsObject.lightToggleWait(500);
lightUtilsObject.outputLightMessage(i + 1, fairyLightsList.get(i).getLightColour(), OFF_STATUS);
lightUtilsObject.lightToggleWait(500);
}
}
}
答案 0 :(得分:0)
使用java Timer
。
下面是一个简单的演示,其功能需要20秒才能完成,但由于定时器限制为30秒,它会在第二次运行时取消执行。
package javaPractice;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask {
@Override
public void run() {
System.out.println("Timer task started at:"+new Date());
completeTask();
System.out.println("Timer task finished at:"+new Date());
}
private void completeTask() {
try {
//assuming it takes 20 secs to complete the task
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
TimerTask timerTask = new MyTimerTask();
//running timer task as daemon thread
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 10*1000);
System.out.println("TimerTask started");
//cancel after sometime
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
System.out.println("TimerTask cancelled");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}