Skip to content

Commit f2b6f4f

Browse files
committed
Allow ScheduledTask.cancel() without actually being started
Throws a NPE without this change.
1 parent 3dea811 commit f2b6f4f

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

metrics/src/main/java/io/avaje/metrics/DScheduledTask.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ public void start() {
6565

6666
@Override
6767
public boolean cancel(boolean mayInterruptIfRunning) {
68+
if (backgroundTask == null) {
69+
return false;
70+
}
6871
return this.backgroundTask.cancel(mayInterruptIfRunning);
6972
}
7073

metrics/src/main/java/io/avaje/metrics/ScheduledTask.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ static Builder builder() {
2525

2626
/**
2727
* Cancel the scheduled task.
28+
* @return true if the task was cancelled otherwise false
2829
*/
2930
boolean cancel(boolean mayInterruptIfRunning);
3031

metrics/src/test/java/io/avaje/metrics/ScheduledTaskTest.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,26 @@
99

1010
class ScheduledTaskTest {
1111

12+
@Test
13+
void stopWithoutStart() {
14+
ScheduledTask task = ScheduledTask.builder()
15+
.schedule(1, 1, TimeUnit.MILLISECONDS)
16+
.task(ScheduledTaskTest::hello)
17+
.build();
18+
19+
task.cancel(true);
20+
}
21+
22+
@Test
23+
void waitWithoutStart() {
24+
ScheduledTask task = ScheduledTask.builder()
25+
.schedule(1, 1, TimeUnit.MILLISECONDS)
26+
.task(ScheduledTaskTest::hello)
27+
.build();
28+
29+
task.waitIfRunning(10, TimeUnit.SECONDS);
30+
}
31+
1232
@Test
1333
void runIt() throws InterruptedException {
1434

0 commit comments

Comments
 (0)