2012-01-18 24 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