Question:
Tell me how to perform certain actions after launching the application and indefinitely once a minute?
Answer:
java.util.Timer:
To use the timer, the task must be inherited from TimerTask
MyTimerTask extends TimerTask {
public void run() {
//Этот метод будет выполняться с нужным нам периодом
}
}
Timer timer = new Timer();
timer.schedule(new MyTimerTask(), 60 * 1000); // Время указывается в миллисекундах
java.util.concurrent.ScheduledExecutorService
For this example, the task must implement the Runnable
interface.
MyTimerTask implenents Runnable {
public void run() {
//Этот метод будет выполняться с нужным нам периодом
}
}
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new MyTimerTask(), 0, 1, TimeUnit.MINUTES);
In general, the method signature is as follows:
scheduler.scheduleAtFixedRate(command, initialDelay, period, unit);
command
– An instance of a class that implements the java.lang.Runnable interface
initialDelay
– delay before the first run
period
– periodicity
unit
– Time unit. java.util.concurrent.TimeUnit
(eg: TimeUnit.MINUTES
)