scheduledthreadpoolexecutor使用(运用Executors.newScheduledThreadPool的任务调度怎么解决)

本文目录
- 运用Executors.newScheduledThreadPool的任务调度怎么解决
- scheduledthreadpoolexecutor保证定时运行么
- Timer和ScheduledThreadPoolExecutor的区别
- ScheduledThreadPoolExecutor删除任务,该怎么解决
- ScheduledThreadPoolExecutor任务超时怎么自动关闭
- scheduledthreadpoolexecutor 初始化多少个
运用Executors.newScheduledThreadPool的任务调度怎么解决
Timer
相信大家都已经非常熟悉 java.util.Timer 了,它是最简单的一种实现任务调度的方法,下面给出一个具体的例子:
清单 1. 使用 Timer 进行任务调度
package com.ibm.scheduler;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest extends TimerTask {
private String jobName = ““;
public TimerTest(String jobName) {
super();
this.jobName = jobName;
}
@Override
public void run() {
System.out.println(“execute “ + jobName);
}
public static void main(String args) {
Timer timer = new Timer();
long delay1 = 1 * 1000;
long period1 = 1000;
// 从现在开始 1 秒钟之后,每隔 1 秒钟执行一次 job1
timer.schedule(new TimerTest(“job1“), delay1, period1);
long delay2 = 2 * 1000;
long period2 = 2000;
// 从现在开始 2 秒钟之后,每隔 2 秒钟执行一次 job2
timer.schedule(new TimerTest(“job2“), delay2, period2);
}
}
Output:
execute job1
execute job1
execute job2
execute job1
execute job1
execute job2
使用 Timer 实现任务调度的核心类是 Timer 和 TimerTask。其中 Timer 负责设定 TimerTask 的起始与间隔执行时间。使用者只需要创建一个 TimerTask 的继承类,实现自己的 run 方法,然后将其丢给 Timer 去执行即可。
Timer 的设计核心是一个 TaskList 和一个 TaskThread。Timer 将接收到的任务丢到自己的 TaskList 中,TaskList 按照 Task 的最初执行时间进行排序。TimerThread 在创建 Timer 时会启动成为一个守护线程。这个线程会轮询所有任务,找到一个最近要执行的任务,然后休眠,当到达最近要执行任务的开始时间点,TimerThread 被唤醒并执行该任务。之后 TimerThread 更新最近一个要执行的任务,继续休眠。
Timer 的优点在于简单易用,但由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。
回页首
ScheduledExecutor
鉴于 Timer 的上述缺陷,Java 5 推出了基于线程池设计的 ScheduledExecutor。其设计思想是,每一个被调度的任务都会由线程池中一个线程去执行,因此任务是并发执行的,相互之间不会受到干扰。需要注意的是,只有当任务的执行时间到来时,ScheduedExecutor 才会真正启动一个线程,其余时间 ScheduledExecutor 都是在轮询任务的状态。
清单 2. 使用 ScheduledExecutor 进行任务调度
package com.ibm.scheduler;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorTest implements Runnable {
private String jobName = ““;
public ScheduledExecutorTest(String jobName) {
super();
this.jobName = jobName;
}
@Override
public void run() {
System.out.println(“execute “ + jobName);
}
public static void main(String args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
long initialDelay1 = 1;
long period1 = 1;
// 从现在开始1秒钟之后,每隔1秒钟执行一次job1
service.scheduleAtFixedRate(
new ScheduledExecutorTest(“job1“), initialDelay1,
period1, TimeUnit.SECONDS);
long initialDelay2 = 1;
long delay2 = 1;
// 从现在开始2秒钟之后,每隔2秒钟执行一次job2
service.scheduleWithFixedDelay(
new ScheduledExecutorTest(“job2“), initialDelay2,
delay2, TimeUnit.SECONDS);
}
}
Output:
execute job1
execute job1
execute job2
execute job1
execute job1
execute job2
清单 2 展示了 ScheduledExecutorService 中两种最常用的调度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。由此可见,ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。
回页首
用 ScheduledExecutor 和 Calendar 实现复杂任务调度
Timer 和 ScheduledExecutor 都仅能提供基于开始时间与重复间隔的任务调度,不能胜任更加复杂的调度需求。比如,设置每星期二的 16:38:10 执行任务。该功能使用 Timer 和 ScheduledExecutor 都不能直接实现,但我们可以借助 Calendar 间接实现该功能。
清单 3. 使用 ScheduledExcetuor 和 Calendar 进行任务调度
package com.ibm.scheduler;
import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExceutorTest2 extends TimerTask {
private String jobName = ““;
public ScheduledExceutorTest2(String jobName) {
super();
this.jobName = jobName;
}
@Override
public void run() {
System.out.println(“Date = “+new Date()+“, execute “ + jobName);
}
/**
* 计算从当前时间currentDate开始,满足条件dayOfWeek, hourOfDay,
* minuteOfHour, secondOfMinite的最近时间
* @return
*/
public Calendar getEarliestDate(Calendar currentDate, int dayOfWeek,
int hourOfDay, int minuteOfHour, int secondOfMinite) {
//计算当前时间的WEEK_OF_YEAR,DAY_OF_WEEK, HOUR_OF_DAY, MINUTE,SECOND等各个字段值
int currentWeekOfYear = currentDate.get(Calendar.WEEK_OF_YEAR);
int currentDayOfWeek = currentDate.get(Calendar.DAY_OF_WEEK);
int currentHour = currentDate.get(Calendar.HOUR_OF_DAY);
int currentMinute = currentDate.get(Calendar.MINUTE);
int currentSecond = currentDate.get(Calendar.SECOND);
//如果输入条件中的dayOfWeek小于当前日期的dayOfWeek,则WEEK_OF_YEAR需要推迟一周
boolean weekLater = false;
if (dayOfWeek 《 currentDayOfWeek) {
weekLater = true;
} else if (dayOfWeek == currentDayOfWeek) {
//当输入条件与当前日期的dayOfWeek相等时,如果输入条件中的
//hourOfDay小于当前日期的
//currentHour,则WEEK_OF_YEAR需要推迟一周
if (hourOfDay 《 currentHour) {
weekLater = true;
} else if (hourOfDay == currentHour) {
//当输入条件与当前日期的dayOfWeek, hourOfDay相等时,
//如果输入条件中的minuteOfHour小于当前日期的
//currentMinute,则WEEK_OF_YEAR需要推迟一周
if (minuteOfHour 《 currentMinute) {
weekLater = true;
} else if (minuteOfHour == currentSecond) {
//当输入条件与当前日期的dayOfWeek, hourOfDay,
//minuteOfHour相等时,如果输入条件中的
//secondOfMinite小于当前日期的currentSecond,
//则WEEK_OF_YEAR需要推迟一周
if (secondOfMinite 《 currentSecond) {
weekLater = true;
}
}
}
}
if (weekLater) {
//设置当前日期中的WEEK_OF_YEAR为当前周推迟一周
currentDate.set(Calendar.WEEK_OF_YEAR, currentWeekOfYear + 1);
}
// 设置当前日期中的DAY_OF_WEEK,HOUR_OF_DAY,MINUTE,SECOND为输入条件中的值。
currentDate.set(Calendar.DAY_OF_WEEK, dayOfWeek);
currentDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
currentDate.set(Calendar.MINUTE, minuteOfHour);
currentDate.set(Calendar.SECOND, secondOfMinite);
return currentDate;
}
public static void main(String args) throws Exception {
ScheduledExceutorTest2 test = new ScheduledExceutorTest2(“job1“);
//获取当前时间
Calendar currentDate = Calendar.getInstance();
long currentDateLong = currentDate.getTime().getTime();
System.out.println(“Current Date = “ + currentDate.getTime().toString());
//计算满足条件的最近一次执行时间
Calendar earliestDate = test
.getEarliestDate(currentDate, 3, 16, 38, 10);
long earliestDateLong = earliestDate.getTime().getTime();
System.out.println(“Earliest Date = “
+ earliestDate.getTime().toString());
//计算从当前时间到最近一次执行时间的时间间隔
long delay = earliestDateLong - currentDateLong;
//计算执行周期为一星期
long period = 7 * 24 * 60 * 60 * 1000;
ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
//从现在开始delay毫秒之后,每隔一星期执行一次job1
service.scheduleAtFixedRate(test, delay, period,
TimeUnit.MILLISECONDS);
}
}
Output:
Current Date = Wed Feb 02 17:32:01 CST 2011
Earliest Date = Tue Feb 8 16:38:10 CST 2011
Date = Tue Feb 8 16:38:10 CST 2011, execute job1
Date = Tue Feb 15 16:38:10 CST 2011, execute job1
scheduledthreadpoolexecutor保证定时运行么
这时候想删除其中一个任务, 看了下API,ScheduledThreadPoolExecutor继承ThreadPoolExecutor类, 此里面有个: ------------------------------------- boolean remove(Runnable task) 从执行程序的内部队列中移除此任务(如果存在),从而如果尚未开始,则其不再运行。 ------------------------------------- 我利用下面方法返回任务列表,执行其contains方法,都表示任务列表里面不包含我的任务。 ------------------------------------- BlockingQueue《Runnable getQueue() 返回此执行程序使用的任务队列。 ------------------------------------- ------解决的方法-------------------------------------------------------- 任务列队里的任务实际上对原始的任务做了包装,所以你删除任务的参数必须是你调用scheduleAtFixedRate返回的参数。 ------解决的方法-------------------------------------------------------- API对此方法有一个说明: 此方法可用作取消方案的一部分。它可能无法移除在放置到内部队列之前已经转换为其他形式的任务。例如,使用 submit 输入的任务可能被转换为维护 Future 状态的形式
Timer和ScheduledThreadPoolExecutor的区别
在实际应用中,有时候我们需要创建一些个延迟的、并具有周期性的任务,比如,我们希望当我们的程序启动后每隔1小时就去做一次日志记录。在JDK中提供了两种方法去创建延迟周期性任务。
Timer
Timer是java.util包下的一个类,在JDK1.3的时候被引入,Timer只是充当了一个执行者的角色,真正的任务逻辑是通过一个叫做TimerTask的抽象类完成的,TimerTask也是java.util包下面的类,它是一个实现了Runnable接口的抽象类,包含一个抽象方法run( )方法,需要我们自己去提供具体的业务实现。
Timer类对象是通过其schedule方法执行TimerTask对象中定义的业务逻辑,并且schedule方法拥有多个重载方法提供不同的延迟与周期性服务。
下面是利用Timer去创建的一个延时周期性任务
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimer {
public static void main(String args) {
String time = new SimpleDateFormat(“HH:mm:ss“).format(new Date());
System.out.println(“Start time : “ + time);
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
String time = new SimpleDateFormat(“HH:mm:ss“).format(new Date());
System.out.println(“Now Time : “ + time);
}
}; //end task
timer.schedule(task, 2000, 3000);
}
}
程序的输出:
Start time : 21:36:08
Now Time : 21:36:10
Now Time : 21:36:13
Now Time : 21:36:16
Now Time : 21:36:19
ScheduledThreadPoolExecutor
在JDK1.5的时候在java.util.concurrent并发包下引入了ScheduledThreadPoolExecutor类,引入它的原因是因为Timer类创建的延迟周期性任务存在一些缺陷, ScheduledThreadPoolExecutor继承了ThreadPoolExecutor,并且实现了ScheduledExecutorService接口, ScheduledThreadPoolExecutor也是通过schedule方法执行Runnable任务的。
我们用 ScheduledThreadPoolExecutor来实现和上述Timer一样的功能
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestScheduledThreadPoolExecutor {
public static void main(String args) {
String time = new SimpleDateFormat(“HH:mm:ss“).format(new Date());
System.out.println(“Start time : “ + time);
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5); //创建5个执行线程
Runnable runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
String time = new SimpleDateFormat(“HH:mm:ss“).format(new Date());
System.out.println(“Now Time : “ + time);
}
};
executor.scheduleWithFixedDelay(runnable, 2, 3, TimeUnit.SECONDS);
}
}
程序的输出:
Start time : 22:12:25
Now Time : 22:12:27
Now Time : 22:12:30
Now Time : 22:12:33
Now Time : 22:12:36
这样看来Timer和 ScheduledThreadPoolExecutor好像没有声明差别,但是 ScheduledThreadPoolExecutor的引入正是由于Timer类存在的一些不足,并且在JDK1.5或更高版本中,几乎没有利用继续使用Timer类,下面说明Timer存在的一些缺点。
单线程
Timer类是通过单线程来执行所有的TimerTask任务的,如果一个任务的执行过程非常耗时,将会导致其他任务的时效性出现问题。而 ScheduledThreadPoolExecutor是基于线程池的多线程执行任务,不会存在这样的问题。
这里我们通过让Timer来执行两个TimerTask任务来说明,其中一个TimerTask的执行过程是耗时的,加入需要2秒。
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class SingleThreadTimer {
public static void main(String args) {
String time = new SimpleDateFormat(“HH:mm:ss“).format(new Date());
System.out.println(“Start time : “ + time);
Timer timer = new Timer();
TimerTask task1 = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
String time = new SimpleDateFormat(“HH:mm:ss“).format(new Date());
System.out.println(“Task1 time : “ + time);
}
};
TimerTask task2 = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String time = new SimpleDateFormat(“HH:mm:ss“).format(new Date());
System.out.println(“task2 time : “ + time);
}
};
timer.schedule(task1, 2000, 1000);
timer.schedule(task2, 2000, 3000);
}
}
这里定义了两个任务,任务1,程序启动2秒后每隔1秒运行一次,任务2,程序启动2秒后,每隔3秒运行1次,然后让Timer同时运行这两个任务
程序的输出如下:
Start time : 22:22:37
Task1 time : 22:22:39
task2 time : 22:22:41
Task1 time : 22:22:41
Task1 time : 22:22:42
task2 time : 22:22:44
Task1 time : 22:22:44
Task1 time : 22:22:45
task2 time : 22:22:47
Task1 time : 22:22:47
Task1 time : 22:22:48
可以分析,无论是任务1还是任务2都没有按照我们设定的预期进行运行,造成这个现象的原因就是Timer类是单线程的。
Timer线程不捕获异常
Timer类中是不捕获异常的,假如一个TimerTask中抛出未检查异常(P.S: java中异常分为两类:checked exception(检查异常)和unchecked exception(未检查异常),对于未检查异常也叫RuntimeException(运行时异常). ),Timer类将不会处理这个异常而产生无法预料的错误。这样一个任务抛出异常将会导致整个Timer中的任务都被取消,此时已安排但未执行的TimerTask也永远不会执行了,新的任务也不能被调度(所谓的“线程泄漏”现象)。
下面就已常见的RuntimeException,ArrayIndexOutOfBoundsException数组越界异常,来演示这个缺点:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimerTask {
public static void main(String args) {
System.out.println(new SimpleDateFormat(“HH:mm:ss“).format(new Date()));
Timer timer = new Timer();
TimerTask task1 = new TimerTask() {
@Override
public void run() {
System.out.println(“1: “ + new SimpleDateFormat(“HH:mm:ss“).format(new Date()));
}
};
TimerTask task2 = new TimerTask() {
@Override
public void run() {
int arr = {1,2,3,4,5};
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int index = (int)(Math.random()*100);
System.out.println(arr[index]);
System.out.println(“2: “ + new SimpleDateFormat(“HH:mm:ss“).format(new Date()));
}
};
timer.schedule(task1, 2000, 3000);
timer.schedule(task2, 2000, 1000);
}
}
程序会在运行过程中抛出数组越界异常,并且整个程序都会被终止,原来完好的任务1也被终止了。
基于绝对时间
Timer类的调度是基于绝对的时间的,而不是相对的时间,因此Timer类对系统时钟的变化是敏感的,举个例子,加入你希望任务1每个10秒执行一次,某个时刻,你将系统时间提前了6秒,那么任务1就会在4秒后执行,而不是10秒后。在 ScheduledThreadPoolExecutor,任务的调度是基于相对时间的,原因是它在任务的内部 存储了该任务距离下次调度还需要的时间(使用的是基于 System#nanoTime实现的相对时间 ,不会因为系统时间改变而改变,如距离下次执行还有10秒,不会因为将系统时间调前6秒而变成4秒后执行)。
基于以上3个弊端,在JDK1.5或以上版本中,我们几乎没有理由继续使用Timer类,ScheduledThreadPoolExecutor可以很好的去替代Timer类来完成延迟周期性任务。
ScheduledThreadPoolExecutor删除任务,该怎么解决
这时候想删除其中一个任务,
看了下API,ScheduledThreadPoolExecutor继承ThreadPoolExecutor类,
此里面有个:
-------------------------------------
boolean remove(Runnable task)
从执行程序的内部队列中移除此任务(如果存在),从而如果尚未开始,则其不再运行。
-------------------------------------
我利用下面方法返回任务列表,执行其contains方法,都表示任务列表里面不包含我的任务。
-------------------------------------
BlockingQueue《Runnable getQueue()
返回此执行程序使用的任务队列。
-------------------------------------
------解决的方法--------------------------------------------------------
任务列队里的任务实际上对原始的任务做了包装,所以你删除任务的参数必须是你调用scheduleAtFixedRate返回的参数。
------解决的方法--------------------------------------------------------
API对此方法有一个说明:
此方法可用作取消方案的一部分。它可能无法移除在放置到内部队列之前已经转换为其他形式的任务。例如,使用 submit 输入的任务可能被转换为维护 Future 状态的形式。
ScheduledThreadPoolExecutor任务超时怎么自动关闭
使用ScheduledThreadPoolExecutor,每隔一个小时去连接指纹机下载考勤记录,有时候指纹机无法返回,导致线程一直在等待,下一个线程无法启动。有没有一个办法,我配置一个超时时间,时间到了,本次任务自动关闭,内存和连接都释放,然后等待下一次的定时到期。
scheduledthreadpoolexecutor 初始化多少个
通过Executors,可以创建3种类型的ThreadPoolExecutor。
- FixedThreadPool
- SingleThreadExecutor
- CachedThreadPool
1.FixedThreadPool
FixedThreadPool被称为可重用固定线程数的线程池。下面是FixedThreadPool的源代码实现。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue《Runnable》());
FixedThreadPool中多余的空闲线程会被立即终止。
FixedThreadPool的execute()运行示意图如下所示。
如果当前运行的线程数小于corePoolSize,则创建新线程来执行任务。
当前运行的线程数等于corePoolSize,将任务加入LinkedBlockingQueue。
线程执行完1中的任务后,会反复从阻塞队列中取任务执行。

更多文章:
易语言网页api接口怎么调用(易语言,怎么读取网页json的api)
2026年10月11日 08:00
majority of(the majority of 和 a majority of的区别以及用法例句)
2026年10月11日 07:40
another time(another time和other time的区别)
2026年10月11日 05:00








