2017-12-27 10 views
1

関数を特定の時間ループさせようとすると、関数の実行が完了するまでに約20秒かかることに注意してください。 fooが実行するために20秒かかる場合一定期間関数をループする方法

long startTime = System.currentTimeMillis(); 
long length = 30000; 
while(System.currentTimeMillis() - startTime <= length){ 
    foo(); // takes 20 seconds to finish executing 
} 

はこれで唯一の欠点は、このコードは30で中断されませんされ、そして意志ループ用:

は明らかの線に沿って何かを使用するオプションがありますwhileの前の20秒がfalseであるため、40秒間実行されます。

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); 
     } 
    } 

} 
+5

[XY通報](http://xyproblem.info/)のように聞こえます。 'foo()'の中身は何ですか? – shmosel

+0

ご質問を理論的ではなく、はるかに具体的にしてください。 –

+0

申し訳ありませんが、これは私の最初の投稿ですので、時間の内容でより良くなるでしょう。 とにかくfoo()はThread.sleep()を含むコードで、実行には約20秒かかります。 –

答えて

0

使用のJava Timer

fooが、このコードスニペットです。

以下は、終了までに20秒かかる機能を持つ簡単なデモですが、30秒のタイマー制限により、2回目の実行で実行をキャンセルします。

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"); 
    } 

} 

Refrence

関連する問題