您的位置:首页 > 其它

Quartz和Timer两种定时器的区别

2018-03-21 15:00 323 查看

1:Quartz:

Spring配置文件:<!-- 配置触发器 -->
<!-- 配置JOB类 -->
<bean id="schedulers" class="com.java.activiti.scheduler.schedulers"></bean>
<!-- 配置JobDetail -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref ="schedulers"></property>
<property name="targetMethod" value = "excute"></property>
</bean>
<!-- 配置trigger -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<!-- 调度程序 -->
<property name="jobDetail" ref="jobDetail"/>
<!-- 表达式(重点) -->
<property name="cronExpression" value="0/5 * * * * ? *"/>
</bean>
<!-- 配置调度中心 -->
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>pom文件加入2个jar包:<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
package com.java.activiti.scheduler;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class schedulers {
private static final Logger logger = Logger.getLogger(schedulers.class);
public void excute() {
logger.debug("开始了哦!");
System.out.println("定时器正在执行");
}
}



2:Timer:

package com.java.activiti.timer;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTest {

public static void main(String[] args) {
Timer timer = new Timer();
Task task = new Task();
timer.schedule(task, new Date(), 1000);
}
}
class Task extends TimerTask{
public void run(){
System.out.println("Timer开始执行!");
}
}




JDK源码分析一下,Timer原理:

Timer源码

public class Timer {
/**
* The timer task queue.  This data structure is shared with the timer
* thread.  The timer produces tasks, via its various schedule calls,
* and the timer thread consumes, executing timer tasks as appropriate,
* and removing them from the queue when they're obsolete.
*/
private final TaskQueue queue = new TaskQueue();

/**
* The timer thread.
*/
private final TimerThread thread = new TimerThread(queue);

这里可以看出,有一个队列(其实是个最小堆),和一个线程对象我们在看一下Timer的构造函数
/**
* Creates a new timer.  The associated thread does <i>not</i>
* {@linkplain Thread#setDaemon run as a daemon}.
*/
public Timer() {
this("Timer-" + serialNumber());
}

这里调用了有参构造函数,进入查看
/**
* Creates a new timer whose associated thread has the specified name.
* The associated thread does <i>not</i>
* {@linkplain Thread#setDaemon run as a daemon}.
*
* @param name the name of the associated thread
* @throws NullPointerException if {@code name} is null
* @since 1.5
*/
public Timer(String name) {
thread.setName(name);
thread.start();
}

这里可以看到,起了一个线程ok,我们再看一下,TimerTask这个类
/**
* A task that can be scheduled for one-time or repeated execution by a Timer.
*
* @author  Josh Bloch
* @see     Timer
* @since   1.3
*/

public abstract class TimerTask implements Runnable {

虽然代码不多,也不贴完,这里看出,是一个实现了Runable接口的类,也就是说可以放到线程中运行的任务这里就清楚了,Timer是一个线程,TimerTask是一个Runable实现类,那只要提交TimerTask对象就可以运行任务了。
public void schedule(TimerTask task, Date firstTime, long period) {
if (period <= 0)
throw new IllegalArgumentException("Non-positive period.");
sched(task, firstTime.getTime(), -period);
}
进入Timer shed(task, firstTime, period)
private void sched(TimerTask task, long time, long period) {
if (time < 0)
throw new IllegalArgumentException("Illegal execution time.");

// Constrain value of period sufficiently to prevent numeric
// overflow while still being effectively infinitely large.
if (Math.abs(period) > (Long.MAX_VALUE >> 1))
period >>= 1;

synchronized(queue) {
if (!thread.newTasksMayBeScheduled)
throw new IllegalStateException("Timer already cancelled.");

synchronized(task.lock) {
if (task.state != TimerTask.VIRGIN)
throw new IllegalStateException(
"Task already scheduled or cancelled");
task.nextExecutionTime = time;
task.period = period;
task.state = TimerTask.SCHEDULED;
}

queue.add(task);
if (queue.getMin() == task)
queue.notify();
}
}

这里主要是queue.add(task)将任务放到最小堆里面,并queue.notity()唤醒在等待的线程那么我们进入Timer类的TimerThread对象查看run方法,因为Timer类里面有个TimerThread 对象是一个线程
public void run() {
try {
mainLoop();
} finally {
// Someone killed this Thread, behave as if Timer cancelled
synchronized(queue) {
newTasksMayBeScheduled = false;
queue.clear();  // Eliminate obsolete references
}
}
}

这里可以看出,在执行一个mainLoop()循环,进入这个循环
/**
* The main timer loop.  (See class comment.)
*/
private void mainLoop() {
while (true) {
try {
TimerTask task;
boolean taskFired;
synchronized(queue) {
// Wait for queue to become non-empty
while (queue.isEmpty() && newTasksMayBeScheduled)
queue.wait();
if (queue.isEmpty())
break; // Queue is empty and will forever remain; die

// Queue nonempty; look at first evt and do the right thing
long currentTime, executionTime;
task = queue.getMin();
synchronized(task.lock) {
if (task.state == TimerTask.CANCELLED) {
queue.removeMin();
continue;  // No action required, poll queue again
}
currentTime = System.currentTimeMillis();
executionTime = task.nextExecutionTime;
if (taskFired = (executionTime<=currentTime)) {
if (task.period == 0) { // Non-repeating, remove
queue.removeMin();
task.state = TimerTask.EXECUTED;
} else { // Repeating task, reschedule
queue.rescheduleMin(
task.period<0 ? currentTime   - task.period
: executionTime + task.period);
}
}
}
if (!taskFired) // Task hasn't yet fired; wait
queue.wait(executionTime - currentTime);
}
if (taskFired)  // Task fired; run it, holding no locks
task.run();
} catch(InterruptedException e) {
}
}

这里忘了说明,TimerTask是按nextExecutionTime进行堆排序的。每次取堆中nextExecutionTime和当前系统时间进行比较,如果当前时间大于nextExecutionTime则执行,如果是单次任务,会将任务从最小堆,移除。否则,更新nextExecutionTime的值 至此,Timer定时任务原理基本理解,单线程 + 最小堆 + 不断轮询3:TimerTask 和 Quartz比较

3.1

   精确度和功能  Quartz可以通过cron表达式精确到特定时间执行,而TimerTask不能。Quartz拥有TimerTask所有的功能,而     TimerTask则没有。

3.2

   Quartz每次执行任务都创建一个新的任务类对象,而TimerTask则每次使用同一个任务类对象。

3.3

Quartz的某次执行任务过程中抛出异常,不影响下一次任务的执行,当下一次执行时间到来时,定时器会再次执行任务;而TimerTask则不同,一旦某个任务在执行过程中抛出异常,则整个定时器生命周期就结束,以后永远不会再执行定时器任务。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: