JAVA-17333 Update Java Timer Article (#13423)

* JAVA-17333 Update Java Timer Article

* JAVA-17333 Rename the test class

---------

Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
timis1 2023-02-08 18:17:09 +02:00 committed by GitHub
parent 9b94733b9a
commit 940cc28ef5
2 changed files with 15 additions and 7 deletions

View File

@ -3,12 +3,24 @@ package com.baeldung.timer;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class NewsletterTask extends TimerTask {
@Override
public void run() {
System.out.println("Email sent at: "
+ LocalDateTime.ofInstant(Instant.ofEpochMilli(scheduledExecutionTime()), ZoneId.systemDefault()));
Random random = new Random();
int value = random.ints(1, 7)
.findFirst()
.getAsInt();
System.out.println("The duration of sending the mail will took: " + value);
try {
TimeUnit.SECONDS.sleep(value);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test;
import java.util.Timer;
class NewsletterTaskUnitTest {
class NewsletterTaskUnitManualTest {
private final Timer timer = new Timer();
@AfterEach
@ -17,17 +17,13 @@ class NewsletterTaskUnitTest {
void givenNewsletterTask_whenTimerScheduledEachSecondFixedDelay_thenNewsletterSentEachSecond() throws Exception {
timer.schedule(new NewsletterTask(), 0, 1000);
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
}
Thread.sleep(20000);
}
@Test
void givenNewsletterTask_whenTimerScheduledEachSecondFixedRate_thenNewsletterSentEachSecond() throws Exception {
timer.scheduleAtFixedRate(new NewsletterTask(), 0, 1000);
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
}
Thread.sleep(20000);
}
}