2013-11-23 44 views
4

如何让一个方法运行5分钟,然后在被布尔函数调用后停止一些帮助。我可以让方法运行正常,但似乎无法为其设置任何计时器,该方法在调用时连续运行或根本不运行。我在这里搜索了一下,发现了一些建议,但到目前为止没有运气。设置方法运行一段时间?

这里就是方法被调用的代码的一部分,受到布尔条件得到满足

public void start() 
{ 
    super.start(); 
    drawing(true); 
} 

public void msgCollision(Actor actor, String s, String s1) 
{ 
    if(boom) 
    { 
     t1 = Time.current(); 
     t2 = Time.current() + 30000L; 
     if(t1 < t2) 
      MarkTarget(); 
    } else 
    if(!boom) 
    { 
     Point3d point3d = new Point3d(); 
     super.pos.getTime(Time.current(), point3d); 
     Vector3d vector3d = new Vector3d(); 
     getSpeed(vector3d); 
     vector3d.x = vector3d.y = vector3d.z = 0.0D; 
     setSpeed(vector3d); 

进出口新的编程和Java,所以请原谅我,如果我失去了一些东西很明显,它的获得MarkTarget()方法运行5分钟,我遇到了麻烦,它似乎连续运行时,布尔热潮被称为t1 < t2,它好像t2永远不会到达,如果我将它改为t2 < t1,那么它不会根本不会像我预料的那样运行。

每次代码运行时是否重置时间?所以在代码再次运行之前5分钟永远不会实现,并且Time.current()会继续运行?或者不是那样工作?我希望5分钟的时间可以从繁荣开始时算起。发生

感谢您的帮助

回答

2

这是因为你可以实例变量之后,一旦权评估T1的值到T2的。

if(boom) 
{ 
    t1 = Time.current(); //t1 is now the current time 
    t2 = Time.current() + 30000L; //t2 is now the current time + 5 minutes 
    if(t1 < t2) //Is t1 smaller then t2? Yes it is! 
     MarkTarget(); //call the function 
    //Anything else? no so we will have had 1 call to it 
} 

你可以,如果你真的想这样做,是这样的:

if (boom) 
{ 
    t1 = Time.current(); 
    t2 = t1 + 30000L; 
    while (t1 < t2) { 
     MarkTarget(); 
     t1 = Time.current(); 
    } 
} 

一定要明白,用这种方式,MarkTarget()将被调用了很多次,每次5分钟。如果你想要它被调用一次,然后等待5分钟:

MarkTarget(); 
while (t1 < t2) { 
    t1 = Time.current(); 
} 
0

问题是,你已经初始化t1和t2在同一个地方。 所以,t2=t1+30000L在任何给定的时间

解决方法:初始化T1ü致电msgCollision(前)和替代t1<t2,使用此条件if((Time.current()-t1)<30000L)

+0

非常感谢您的帮助,我认为这可能是某种方式的时间宣布,但无法弄清楚我错了,@ FlorisVelleman @二 – user2558274

0

那么,如果你不断地调用该函数,你可以写这样的:

if(boom) { 
    if (timeDone < 0) { 
    timeDone = System.currentTimeMillis() + 1000 * 60 * 5; // now + 5 minutes 
    } 
    MarkTarget(); 
    if (System.currentTimeMillis() >= timeDone) { // now >= done-time? 
    boom = false; 
    timeDone = -1; 
    } 
} else { 

否则,您可能需要查看Timer类或更复杂的ScheduledThreadPoolExecutor。