-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScheduledTask.java
More file actions
49 lines (42 loc) · 1.53 KB
/
ScheduledTask.java
File metadata and controls
49 lines (42 loc) · 1.53 KB
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
package com.taskscheduler;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Schedules tasks to run after a delay or at a fixed rate,
* then submits them into the custom ThreadPool for execution.
*/
public class ScheduledTask {
private final ThreadPool threadPool;
private final ScheduledExecutorService scheduler;
public ScheduledTask(ThreadPool threadPool) {
this.threadPool = threadPool;
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "Scheduler");
t.setDaemon(true);
return t;
});
}
/**
* Submit a task to the pool after a fixed delay.
*/
public void scheduleOnce(String name, Runnable runnable, long delay, TimeUnit unit) {
scheduler.schedule(() -> {
System.out.printf("[Scheduler] Firing delayed task: %s%n", name);
threadPool.submit(name, runnable);
}, delay, unit);
}
/**
* Submit a task to the pool repeatedly at a fixed rate.
*/
public void scheduleRepeating(String name, Runnable runnable, long initialDelay,
long period, TimeUnit unit) {
scheduler.scheduleAtFixedRate(() -> {
System.out.printf("[Scheduler] Firing repeating task: %s%n", name);
threadPool.submit(name, runnable);
}, initialDelay, period, unit);
}
public void shutdown() {
scheduler.shutdown();
}
}