2012-01-18 4 views
2

배경 (아래 질문을 건너 뛸 수 있습니다 ...)자바 : 더 완전한 재 시도하는 경우, 최대 n 초에 대한 기능을 위해 기다려

는 현재 레고 마인드 스톰 로봇과 ICommand의 API (HTTP 작업 : //lejos.sourceforge.net/p_technologies/nxt/icommand/api/index.html).

모터 제어 방법 중 하나에 문제가 있습니다. 이 메서드는 주어진 각도로 모터를 회전합니다.

Motor.A.rotateTo(target); 

이 함수는 모터가 이동을 완료 할 때까지 반환되지 않습니다. 이것은 괜찮지 만 때로는 모터가 멈추지 않고 무기한으로 계속 작동하여 프로그램을 중지합니다.

질문

어쨌든 내가 너무 프로그램이 반환하는 방법 Motor.A.rotateTo(target); 최대 N초을 대기가 할 수입니다. 그리고 나서 그 시간에 돌아 오지 않았다면 다시 메소드를 호출하십시오. (성공할 때까지 반복 될 수 있다면 더 좋을 것입니다.)

감사합니다. 도움을 주시면 감사하겠습니다.

안부, 조

편집 : Motor.A.rotateTo(target);Motor#rotate(long count, boolean returnNow)에 대한

+0

가능한 중복이 지정된 시간 내에 함수의 실행을 중지하는 것이 가능 Java에서?] (http://stackoverflow.com/questions/3183722/is-it-possible-to-stop-a-functions-execution-within-a-specified-time-in-java) – Perception

+0

하지만 실행 중간에 메소드를 중지하면 객체에 일관성없는 상태가 발생합니까? – Tudor

+0

@ Tudor Ah yeh, 예치. 나는'Motor.A.rotateTo (target); '이라고 쓰고 싶었다. 내 실수였다. 모터는 타코 카운터 (tacho-counter)를 가지고있어 얼마나 시계 방향으로 돌았는지 (시계 반대 방향, 시계 반대 방향, 타코 = 1도)를 기록합니다. 그래서 간단히 그 메소드를 다시 호출 할 수 있으며 목표 tacho-count에 도달 할 때까지 회전합니다. – Leech

답변

1

별도의 스레드에서 rotate를 실행하고 결과를 기다리는 ExecutorService 또는 다른 스레딩 솔루션을 사용할 수 있습니다. 여기에 또한 시간의 주어진 숫자를 시도 완벽한 프로그램입니다 :

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.A.rotate(target);에서 수정? 특정 시간 후에 모터가 멈추게하려면 stop()으로 전화하십시오.

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

답장을 보내 주셔서 감사합니다. 그러나 모터가 회전을 완료했는지 어떻게 알 수 있습니까? – Leech

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