How to create a timer in the boost method, after which the stopboost method starts?

I looked on the stack and found a timer, but I don’t know how to use it. Timer.

public void boost() { unboost = false; velocity.y = 200; } public void stopboost() { velocity.y = 0; } 

2 answers 2

I explain. We need a class Timer , which is designed to set pending tasks.

The public void schedule method (TimerTask task, long delay) works quite simply. The second argument is the delay in milliseconds. The first argument is an instance of the TimerTask object. This abstract class is extremely simple and requires only one method to be implemented:

 public class MyTimerTask extends TimerTask { @Override public void run() {...} } 

So, we need an instance of this class. How can we get it? The easiest way to declare an anonymous class.

 TimerTask tt = new TimerTask() { @Override public void run() { // тут наш код } } 

In order to use Timer, you need to create its instance:

 Timer timer = new java.util.Timer(); 

We give him our TimerTask:

 timer.schedule(tt, 1000); 

If we no longer need Timer, then we can not assign it to a variable, but execute the method on the newly created instance and forget about it:

 new java.util.Timer().schedule(tt, 1000); 

Since we no longer need TimerTask either, we can create it directly in the method call:

 public void boost() { //какой-то код метода new java.util.Timer().schedule( new TimerTask() { public void run() { stopboost(); } }, 1000 ); //дальше код метода } public void stopboost() { velocity.y = 0; } 

And finally, if the stopboost method exists only for the sake of this timer, then we also exclude it (inline is called)

 public void boost() { //какой-то код метода new java.util.Timer().schedule( new TimerTask() { public void run() { velocity.y = 0; } }, 1000 ); //дальше код метода } 

    why not do so

     public void boost() { unboost = false; velocity.y = 200; try { Thread.sleep(1000); // 1000 это 1 секунда stopboost(); } catch (Exception ex) { } } public void stopboost() { velocity.y = 0; } 
    • You so stop the whole flow. - Nick Volynkin
    • With this approach, the main thread just hangs. - Alexander
    • You are right, if this is the main thread this is a problem. This is me not in the main thread, I propose to do it at least rannable. - Saidolim
    • one
      @SaidolimDjuraev: in general, Timer does just that - starts a waiting thread, which then executes TimerTask. - Nick Volynkin