From e7b46313fba5c490f414e43de29e17fc51bef989 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Sat, 5 Nov 2022 10:53:30 +0000 Subject: [PATCH] [JAVA-13957] Added example for Timer functionality (#12906) Co-authored-by: panagiotiskakos --- .../startathread/TimerDemoExample.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-simple/src/main/java/com/baeldung/concurrent/startathread/TimerDemoExample.java diff --git a/core-java-modules/core-java-concurrency-simple/src/main/java/com/baeldung/concurrent/startathread/TimerDemoExample.java b/core-java-modules/core-java-concurrency-simple/src/main/java/com/baeldung/concurrent/startathread/TimerDemoExample.java new file mode 100644 index 0000000000..ad59d451d4 --- /dev/null +++ b/core-java-modules/core-java-concurrency-simple/src/main/java/com/baeldung/concurrent/startathread/TimerDemoExample.java @@ -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(); + } +}