ScheduledThreadPoolExecutor的使用

Java Executor框架提供了ThreadPoolExecutor类去执行Callable和Runnable任务,这样避免了大量的复杂代码的操作,但是有时你需要定时去执行你的任务,这个时候你就要使用ScheduledThreadPoolExecutor类了。

先写个基本的任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Task implements Runnable
{
private String name;
public Task(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public void run()
{
try {
System.out.println("Doing a task during : " + name + " - Time - " + new Date());
}
catch (Exception e) {
e.printStackTrace();
}
}
}

一段时间后执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ScheduledThreadPoolExecutorExample
{
public static void main(String[] args)
{
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
Task task1 = new Task ("Demo Task 1");
Task task2 = new Task ("Demo Task 2");
System.out.println("The time is : " + new Date());
executor.schedule(task1, 5 , TimeUnit.SECONDS);
executor.schedule(task2, 10 , TimeUnit.SECONDS);
try {
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
}
}

The time is : Tue Jan 25 16:14:07 IST 2017
Doing a task during : Demo Task 1 - Time - Tue Jan 25 16:14:12 IST 2017
Doing a task during : Demo Task 2 - Time - Tue Jan 25 16:14:17 IST 2017

执行任务时间片的形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ScheduledThreadPoolExecutorExample
{
public static void main(String[] args)
{
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Task task1 = new Task ("Demo Task 1");
System.out.println("The time is : " + new Date());
ScheduledFuture<?> result = executor.scheduleAtFixedRate(task1, 2, 5, TimeUnit.SECONDS);
try {
TimeUnit.MILLISECONDS.sleep(20000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
}
}

Output:

The time is : Tue Jan 25 16:20:12 IST 2017
Doing a task during : Demo Task 1 - Time - Tue Jan 25 16:20:14 IST 2017
Doing a task during : Demo Task 1 - Time - Tue Jan 25 16:20:19 IST 2017
Doing a task during : Demo Task 1 - Time - Tue Jan 25 16:20:24 IST 2017
Doing a task during : Demo Task 1 - Time - Tue Jan 25 16:20:29 IST 2017