-
Notifications
You must be signed in to change notification settings - Fork 68
/
UnleashScheduledExecutorImpl.java
60 lines (48 loc) · 2 KB
/
UnleashScheduledExecutorImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package io.getunleash.util;
import io.getunleash.lang.Nullable;
import java.util.concurrent.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UnleashScheduledExecutorImpl implements UnleashScheduledExecutor {
private static final Logger LOG = LoggerFactory.getLogger(UnleashScheduledExecutorImpl.class);
@Nullable private static UnleashScheduledExecutorImpl INSTANCE;
private final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;
private final ExecutorService executorService;
public UnleashScheduledExecutorImpl() {
ThreadFactory threadFactory =
runnable -> {
Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setName("unleash-api-executor");
thread.setDaemon(true);
return thread;
};
this.scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1, threadFactory);
this.scheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true);
this.executorService = Executors.newSingleThreadExecutor(threadFactory);
}
public static synchronized UnleashScheduledExecutorImpl getInstance() {
if (INSTANCE == null) {
INSTANCE = new UnleashScheduledExecutorImpl();
}
return INSTANCE;
}
@Override
public @Nullable ScheduledFuture setInterval(
Runnable command, long initialDelaySec, long periodSec) {
try {
return scheduledThreadPoolExecutor.scheduleAtFixedRate(
command, initialDelaySec, periodSec, TimeUnit.SECONDS);
} catch (RejectedExecutionException ex) {
LOG.error("Unleash background task crashed", ex);
return null;
}
}
@Override
public Future<Void> scheduleOnce(Runnable runnable) {
return (Future<Void>) executorService.submit(runnable);
}
@Override
public void shutdown() {
this.scheduledThreadPoolExecutor.shutdown();
}
}