2016-07-25 49 views
0

簡單的問題在這裏的條件語句,我需要執行只有經過特定的時間段已經過去(以毫秒爲單位)一定的方法:爪哇 - 基於毫秒

static double incrTrueBinaryErr = 62.5; 
static double incrTrueBinaryMov = 31.25; 
static double incr01001 = 360000; 
static double incr_1101 = 125; 
static double incr05008 = 3600000; 
static double incr10004 = 1024000; 
static double incr22000 = 1000; 
static double incr22001 = 1000; 

Date currDate; 

    while (true) 
    { 
    currDate = new Date(); 

    if (currDate.getTime() == currDate.getTime() + incrTrueBinaryErr) 
     //do stuff 

    if (currDate.getTime() == currDate.getTime() + incrTrueBinaryMov) 
     //do stuff 

    if (currDate.getTime() == currDate.getTime() + incr01001) 
     //do stuff 

    if (currDate.getTime() == currDate.getTime() + incr_1101) 
     //do stuff 

    if (currDate.getTime() == currDate.getTime() + incr05008) 
     //do stuff 

    if (currDate.getTime() == currDate.getTime() + incr10004) 
     //do stuff 

    if (currDate.getTime() == currDate.getTime() + incr22000) 
     //do stuff 

    if (currDate.getTime() == currDate.getTime() + incr22001) 
     //do stuff 

    } 

然而,我的計劃從來沒有碰到任何這些因爲時間間隔有多特殊。

要做到這一點,最好的方法是什麼?

+0

嘗試獲得'While'循環之外的時間...或者使用sheduled執行器[請檢查此答案](http://stackoverflow.com/questions/20988664/calling-executorservice-after-some-interval - 時間).. –

+0

你的問題不清楚。你想跑幾次,每次都有不同的延遲? –

回答

1

只有在incr01001 == 0的情況下,這種表達currDate.getTime() == currDate.getTime() + incr01001纔會評估爲true。出於同樣的原因x == x + y只有當y == 0

+0

所以你說的是,我需要一個wait()或sleep()命令才能達到這些增量中的任何一個? – Sean

+0

取決於你想要什麼。你想在特定的時間點執行一部分代碼嗎?或者在前一個塊執行後經過了特定的時間? –

+0

我需要調用一個調用新的Date()命令的方法,該命令將時間字段賦值爲寫入另一個文件,因此它調用一個方法,然後創建一個新的時間戳,希望增加時間離開currDate – Sean

1

只執行之後的特定時間段已經過去(以毫秒爲單位)一定的方法:

您可以使用Thread.sleep(long milliseconds)方法來做到這一點。

try{ 
    Thread.sleep(5000);//for 5 seconds 
} catch(Exception ex){ 
    System.out.println("Error: "+ex.getMessage()); 
} 
+0

如果我理解正確,這不會有他們想要的功能。這假設他們知道需要多少時間,什麼時候該發生什麼應該取決於時間。這隻能在他的「if」塊中等待他的一個動作,而不是全部檢查。 – 17slim

0

先嚐試讓時間你雖然外塊:

Date date = new Date(); 
while (true) 
{ 
    currDate = new Date(); 

    if (currDate.getTime() == date.getTime() + incrTrueBinaryErr) 
    //do stuff 
    //etc. 
} 

這樣while循環不保留重新分配的日期。

這也可能是有點過於具體,就像你說的,讓你的if塊可能:

long timeDifference = date.getTime()+incrTrueBinaryErr-currDate.getTime(); 

if (Math.abs(timeDifference)<5l) 
    //do stuff 

如果新的時間是你想要的5毫秒內,「做的東西」。