综观目前的 Web 应用,多数应用都具备任务调度的功能。本文由浅入深介绍了几种任务调度的 Java 实现方法,包括 Timer,Scheduler, Quartz 以及 JCron Tab,并对其优缺点进行比较,目的在于给需要开发任务调度的程序员提供有价值的参考。
任务调度是指基于给定时间点,给定时间间隔或者给定执行次数自动执行任务。本文由浅入深介绍四种任务调度的 Java 实现:
- Timer
- ScheduledExecutor
- 开源工具包 Quartz
- 开源工具包 JCronTab
此外,为结合实现复杂的任务调度,本文还将介绍 Calendar 的一些使用方法。
Timer
相信大家都已经非常熟悉 java.util.Timer 了,它是最简单的一种实现任务调度的方法,下面给出一个具体的例子:
package org.js.test;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created with IntelliJ IDEA.
* User: dev02
* Date: 16-1-27
* Time: 下午2:55
* To change this template use File | Settings | File Templates.
*/
public class TimerTest extends TimerTask{
private String jobname=null;
public TimerTest(String jobname) {
this.jobname = jobname;
}
@Override
public void run() {
System.out.println("job:"+jobname);
System.out.println("sysdate:"+(new Date()));
try {
Thread.currentThread().sleep(4300);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("job:"+jobname);
System.out.println("sysdate:"+(new Date()));
//To change body of implemented methods use File | Settings | File Templates.
}
public static void main(String[] args){
Timer timer=new Timer();
long delay1=1*1000;
long period=1500;
//1s后,每隔1.5s执行一次
timer.schedule(new TimerTest("job1"),delay1,period);
//2s后,每隔3s执行一次
long delay2=2*1000;
long period2=3000;
timer.schedule(new TimerTest("job2"),delay2,period2);
}
}
package org.js.test;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created with IntelliJ IDEA.
* User: dev02
* Date: 16-1-27
* Time: 下午2:55
* To change this template use File | Settings | File Templates.
*/
public class TimerTest extends TimerTask{
private String jobname=null;
public TimerTest(String jobname) {
this.jobname = jobname;
}
@Override
public void run() {
System.out.println("job:"+jobname);
System.out.println("sysdate:"+(new Date()));
try {
Thread.currentThread().sleep(4300);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("job:"+jobname);
System.out.println("sysdate:"+(new Date()));
//To change body of implemented methods use File | Settings | File Templates.
}
public static void main(String[] args){
Timer timer=new Timer();
long delay1=1*1000;
long period=1500;
//1s后,每隔1.5s执行一次
timer.schedule(new TimerTest("job1"),delay1,period);
//2s后,每隔3s执行一次
long delay2=2*1000;
long period2=3000;
timer.schedule(new TimerTest("job2"),delay2,period2);
}
}
输出结果:
使用 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 都是在轮询任务的状态。
package org.js.test;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created with IntelliJ IDEA.
* User: dev02
* Date: 16-1-28
* Time: 下午1:54
* To change this template use File | Settings | File Templates.
*/
public class ScheduledExecutorTest implements Runnable{
private String jobname="";
public ScheduledExecutorTest(String jobname) {
this.jobname = jobname;
}
public void run() {
System.out.println("job:"+jobname);
System.out.println("sysdate:"+(new Date()));
try {
Thread.currentThread().sleep(4300);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("job:"+jobname);
System.out.println("sysdate:"+(new Date()));
//To change body of implemented methods use File | Settings | File Templates.
}
public static void main(String[] args){
ScheduledExecutorService services= Executors.newScheduledThreadPool(10);
long delay1=1;
long period=2;
//1s后,每隔1s执行一次
services.scheduleAtFixedRate( new ScheduledExecutorTest("job1"),delay1,period, TimeUnit.SECONDS);
long delay2=2;
long period2=3;
services.scheduleAtFixedRate( new ScheduledExecutorTest("job2"),delay2,period2, TimeUnit.SECONDS); }
}
package org.js.test;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created with IntelliJ IDEA.
* User: dev02
* Date: 16-1-28
* Time: 下午1:54
* To change this template use File | Settings | File Templates.
*/
public class ScheduledExecutorTest implements Runnable{
private String jobname="";
public ScheduledExecutorTest(String jobname) {
this.jobname = jobname;
}
public void run() {
System.out.println("job:"+jobname);
System.out.println("sysdate:"+(new Date()));
try {
Thread.currentThread().sleep(4300);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("job:"+jobname);
System.out.println("sysdate:"+(new Date()));
//To change body of implemented methods use File | Settings | File Templates.
}
public static void main(String[] args){
ScheduledExecutorService services= Executors.newScheduledThreadPool(10);
long delay1=1;
long period=2;
//1s后,每隔1s执行一次
services.scheduleAtFixedRate( new ScheduledExecutorTest("job1"),delay1,period, TimeUnit.SECONDS);
long delay2=2;
long period2=3;
services.scheduleAtFixedRate( new ScheduledExecutorTest("job2"),delay2,period2, TimeUnit.SECONDS); }
}
输出结果:
使用ScheduledExecutor可以看出,我们job执行的时候线程池中一个线程去执行。这和之前使用Timer的串行执行不一致。
ScheduledExecutor 和 Calendar 实现复杂任务调度
Timer 和 ScheduledExecutor 都仅能提供基于开始时间与重复间隔的任务调度,不能胜任更加复杂的调度需求。比如,设置每星期二的 16:38:10 执行任务。该功能使用 Timer 和 ScheduledExecutor 都不能直接实现,但我们可以借助 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);
}
}
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);
}
}
/**
输出结果:
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
*/
/**
输出结果:
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
*/
实现了每星期二 16:38:10 调度任务的功能。其核心在于根据当前时间推算出最近一个星期二 16:38:10 的绝对时间,然后计算与当前时间的时间差,作为调用 ScheduledExceutor 函数的参数。计算最近时间要用到 java.util.calendar 的功能。首先需要解释 calendar 的一些设计思想。Calendar 有以下几种唯一标识一个日期的组合方式:
YEAR + MONTH + DAY_OF_MONTH
YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
YEAR + DAY_OF_YEAR
YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
上述组合分别加上 HOUR_OF_DAY + MINUTE + SECOND 即为一个完整的时间标识。本例采用了最后一种组合方式。输入为 DAY_OF_WEEK, HOUR_OF_DAY, MINUTE, SECOND 以及当前日期 , 输出为一个满足 DAY_OF_WEEK, HOUR_OF_DAY, MINUTE, SECOND 并且距离当前日期最近的未来日期。计算的原则是从输入的 DAY_OF_WEEK 开始比较,如果小于当前日期的 DAY_OF_WEEK,则需要向 WEEK_OF_YEAR 进一, 即将当前日期中的 WEEK_OF_YEAR 加一并覆盖旧值;如果等于当前的 DAY_OF_WEEK, 则继续比较 HOUR_OF_DAY;如果大于当前的 DAY_OF_WEEK,则直接调用 java.util.calenda 的 calendar.set(field, value) 函数将当前日期的 DAY_OF_WEEK, HOUR_OF_DAY, MINUTE, SECOND 赋值为输入值,依次类推,直到比较至 SECOND。读者可以根据输入需求选择不同的组合方式来计算最近执行时间。
可以看出,用上述方法实现该任务调度比较麻烦,这就需要一个更加完善的任务调度框架来解决这些复杂的调度问题。幸运的是,开源工具包 Quartz 与 JCronTab 提供了这方面强大的支持。