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 ); //дальше код метода }