2012-01-18 81 views
2

背景(可以跳過下面質疑...)的Java:等待功能了n秒,如果沒有完整的重試

目前與樂高機器人機器人和API的ICommand(HTTP工作: //lejos.sourceforge.net/p_technologies/nxt/icommand/api/index.html)。

在使用其中一種電機控制方法時遇到了一些麻煩。該方法通過給定的角度旋轉電機:

Motor.A.rotateTo(target); 

此功能不會返回,直到電機已經完成運動。這很好,但有時電機無法停止並將無限期地繼續,從而停止程序。

問題

反正我有可以使程序等待長達ñ秒的方法Motor.A.rotateTo(target);返回。然後如果在那段時間還沒有返回,那麼再次調用該方法。 (如果這可能會成功,直到它會更好。)

感謝您的閱讀,任何幫助將不勝感激。

問候, 喬

編輯:從Motor.A.rotate(target);更正爲Motor.A.rotateTo(target);

+0

可能重複是否可以在規定時間內停止功能的執行在Java?](http://stackoverflow.com/questions/3183722/is-it-possible-to-stop-a-functions-execution-within-a-specified-time-in-java) – Perception 2012-01-18 18:04:26

+0

但不會在執行過程中停止方法會導致對象中的狀態不一致? – Tudor 2012-01-18 18:12:57

+0

@Tudor啊,你會的。我的意思是寫'Motor.A.rotateTo(目標);'對不起我的錯誤!馬達有轉速計,它們記錄它們轉過的距離(正向順時針,負向逆時針,1轉速= 1度)。所以我可以簡單地重新調用這個方法,它會旋轉,直到它達到目標轉速計數。 – Leech 2012-01-18 18:47:50

回答

1

您可以使用ExecutorService或其他線程解決方案在一個單獨的線程中運行rotate並等待結果。下面是一個完整的程序,也試給定的次數:

public static void main(String[] args) throws TimeoutException { 
    final ExecutorService pool = Executors.newFixedThreadPool(10); 
    runWithRetry(pool, 5); //run here 
} 

public static void runWithRetry(final ExecutorService pool, final int retries) throws TimeoutException { 
     final Future<?> result = pool.submit(new Runnable() { 
      @Override 
      public void run() { 
       Motor.A.rotate(angle); 
      } 
     }); 
     try { 
      result.get(1, TimeUnit.SECONDS); //wait here 
     } catch (InterruptedException e) { 
      throw new RuntimeException(e.getCause()); 
     } catch (ExecutionException e) { 
      throw new RuntimeException(e.getCause()); 
     } catch (TimeoutException e) { 
      if (retries > 1) { 
       runWithRetry(pool, retries - 1); //retry here 
      } else { 
       throw e; 
     } 
    } 
} 
1

什麼Motor#rotate(long count, boolean returnNow)?如果您希望電機在特定時間後停止,您可以致電stop()

Motor.A.rotate(150, true); 
Thread.sleep(3000); 
Motor.A.stop(); 
+0

感謝您的回覆,我曾考慮過這個問題,但是如何知道電機是否完成了旋轉? – Leech 2012-01-18 18:12:37

0

什麼沿着線的東西:

int desiredPosition = Motor.A.getTachoCount() + ANGLE_TO_TURN; 
long timeout = System.currentTimeMillis + MAX_TIME_OUT; 
Motor.A.forward(); 
while (timeout>System.currentTimeMillis && desiredPosition>Motor.A.getTachoCount()); //wait for the motor to reach the desired angle or the timeout to occur 
Motor.A.stop(); 
的[
+0

類似的東西也起作用。 – Leech 2012-01-21 20:40:42