[JAVA-13957] Added example for Timer functionality (#12906)

Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com>
This commit is contained in:
panos-kakos 2022-11-05 10:53:30 +00:00 committed by GitHub
parent 7313894322
commit e7b46313fb
1 changed files with 39 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package com.baeldung.concurrent.startathread;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerDemoExample {
private void scheduleOnce() {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread()
.getName());
}
};
Timer timer = new Timer("Timer");
long delay = 1000L;
timer.schedule(task, delay);
}
private void scheduleRecurrently() {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Recurrent Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread()
.getName());
}
};
Timer timer = new Timer("Timer");
long delay = 1000L;
final long period = 1000L;
timer.scheduleAtFixedRate(task, delay, period);
}
public static void main(String[] args) {
TimerDemoExample timerDemoExample = new TimerDemoExample();
timerDemoExample.scheduleOnce();
timerDemoExample.scheduleRecurrently();
}
}