`
yuhen78
  • 浏览: 14592 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

Thread, TimerTask 与 Quartz 实现任务调度

阅读更多

Thread, TimerTask  与 Quartz 实现任务调度 :
任务调度 :每过一段时间,系统自动执行某任务操作。

一、线程池方式:
import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DBThread {
  private ScheduledExecutorService scheduler;  //它可另行安排在给定的延迟后运行命令,或者定期执行命令。
  public static void main(String [] arg){
  new DBThread().start();
  }
 private void start() {
       Calendar cal = Calendar.getInstance();   
      cal.setTimeInMillis(System.currentTimeMillis()); //获取系统当前时间
       scheduler = Executors.newScheduledThreadPool(1);  // 创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。
      // 创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后 在 initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。
    scheduler.scheduleAtFixedRate(runnable,0,5,TimeUnit.SECONDS); 
//scheduleAtFixedRate 如果任务的任何一个执行遇到异常,则后续执行都会被取消
  //参数介绍 
     runnable :需要调度的任务
      0:首次执行的延迟时间    
      5: 连续执行之间的周期
      TimeUnit.SECONDS :0和5 参数的时间单位 
      }
   Runnable runnable = new Runnable() {
    public void run() {
        System.out.println("running...");//调用执行任务
    }
  };
}

结合Spring框架使用:
1.TimerTask 方式简单调度:(缺点: Timer无法精确指定何时运行)
public class TimerTask extends java.util.TimerTask {
 @Override
 public void run() {
  // TODO Auto-generated method stub
      System.out.println("TimerTask方式调度的执行的方法");
 }
}
相关配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!--配置实现类-->   
    <bean id="timeTask" class="com.spring.TimerTask"></bean>  
    <bean id="TimeTasks"    class="org.springframework.scheduling.timer.ScheduledTimerTask" >
      <property name="timerTask" ref="timeTask"></property>  
        <!-- 指定任务运行周期,单位毫秒 -->  
        <property name="period" value="1000"></property>  
        <!-- 指定任务延时时间,即第一次运行之前等待时间,单位毫秒 -->  
        <property name="delay" value="1000"></property>  
    </bean> 
    <bean class="org.springframework.scheduling.timer.TimerFactoryBean">
      <property name="scheduledTimerTasks">  
            <list>  
                <ref bean="TimeTasks"/>  
            </list>     
        </property>  
    </bean>
</beans>

2.Quartz实现调度:
2.1. MethodInvokingJobDetailFactoryBean 直接调用需要调度的方法
public class MyQuartz {
 public void getHello()
 {
   System.out.println("hello");  
 }

}
相关配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="myQuartz" class="com.spring.MyQuartz"></bean>
      
    <bean id="newJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
        <property name="targetObject" ref="myQuartz"></property>  
        <property name="targetMethod" value="getHello"></property>  
    </bean>  
     
   <bean id="simplerTrigger2" class="org.springframework.scheduling.quartz.SimpleTriggerBean">  
        <property name="jobDetail" ref="newJob"></property>  

        <!-- 设置延迟工作的第一次执行,单位毫秒 -->  
        <property name="startDelay" value="1000"></property>  

        <!-- 设置调度任务频度,单位毫秒 -->  
        <property name="repeatInterval" value="1000"></property>  
  </bean>  

<!-- 设置调度周期 --> 
  <bean id="cronTrigger2" class="org.springframework.scheduling.quartz.CronTriggerBean">  
        <property name="jobDetail" ref="newJob"></property>  
        <property name="cronExpression" value="0 59 23 * * ?"></property>
  </bean> 
   
  <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
        <!-- 接受一组触发器,可以接受一个列表 -->  
        <property name="triggers">  
            <list>  
                <ref bean="simplerTrigger2"/>  
                 <ref bean="cronTrigger"/>  
            </list>  
        </property>  
  </bean>
</beans>

2.2:继承QuartzJobBean 类方式调度
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.*;

public class MyQuartzJob extends QuartzJobBean {

 @Override
 protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
  
  System.out.println("running...");
  
  }  
}
相关配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
 <bean id="quartzJob" class="org.springframework.scheduling.quartz.JobDetailBean">  
        <property name="jobClass" value="com.spring.MyQuartzJob"></property>  
        <!-- 接受一个Map,其中包含了需要设置给jobClass的各种属性 -->  
        <property name="jobDataAsMap">  
            <map></map>  
        </property>  
   </bean>  
 <bean id="simplerTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">  
        <property name="jobDetail" ref="quartzJob"></property>  
        <!-- 设置延迟工作的第一次执行,单位毫秒 -->  
        <property name="startDelay" value="1000"></property>  
        <!-- 设置调度任务频度,单位毫秒 -->  
        <property name="repeatInterval" value="1000"></property>  
    </bean>  
    <!-- 设置调度时间 --> 
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
        <property name="jobDetail" ref="quartzJob"></property>  
        <property name="cronExpression" value="0 59 23 * * ?"></property>
   </bean> 
   <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
        <!-- 接受一组触发器,可以接受一个列表 -->  
        <property name="triggers">  
            <list>  
                <ref bean="simplerTrigger"/>  
                <ref bean="cronTrigger"/>  
            </list>  
        </property>  
    </bean> 
  </beans>

 
表达式 解释
0 0 12 * * ? 在每天中午12:00触发
0 15 10 ? * * 每天上午10:15 触发
0 15 10 * * ? 每天上午10:15 触发
0 15 10 * * ? * 每天上午10:15 触发
0 15 10 * * ? 2005 在2005年中的每天上午10:15 触发
0 * 14 * * ? 每天在下午2:00至2:59之间每分钟触发一次
0 0/5 14 * * ? 每天在下午2:00至2:59之间每5分钟触发一次
0 0/5 14,18 * * ? 每天在下午2:00至2:59和6:00至6:59之间的每5分钟触发一次
0 0-5 14 * * ? 每天在下午2:00至2:05之间每分钟触发一次
0 10,44 14 ? 3 WED 每三月份的星期三在下午2:00和2:44时触发
0 15 10 ? * MON-FRI 从星期一至星期五的每天上午10:15触发
0 15 10 15 * ? 在每个月的每15天的上午10:15触发
0 15 10 L * ? 在每个月的最后一天的上午10:15触发
0 15 10 ? * 6L 在每个月的最后一个星期五的上午10:15触发
0 15 10 ? * 6L 2002-2005 在2002, 2003, 2004 and 2005年的每个月的最后一个星期五的上午10:15触发
0 15 10 ? * 6#3 在每个月的第三个星期五的上午10:15触发
0 0 12 1/5 * ? 从每月的第一天起每过5天的中午12:00时触发
0 11 11 11 11 ? 在每个11月11日的上午11:11时触发.

分享到:
评论

相关推荐

    java定时器

    Java中的定时任务实现方式 在Java中实现定时任务主要有两种方式: - 使用 `java.util.Timer` - 使用第三方库如 Quartz 这两种方式各有优缺点。例如,`java.util.Timer` 更加简单易用,但其功能相对有限;而 ...

    java定时检测系统

    1. **Java定时器(java.util.Timer 和 TimerTask)**:Java标准库提供了`Timer`类和`TimerTask`类来实现定时任务。通过创建一个`Timer`实例,可以调度`TimerTask`在指定的时间间隔内执行。例如,可以创建一个`...

    Java定时任务的三种实现方式

    在选择定时任务实现方式时,需要考虑以下几个因素: 1. 简单任务:如果任务简单,对性能要求不高,Timer和TimerTask可能是合适的选择。 2. 高并发和线程安全:ScheduledExecutorService在多线程环境下表现更稳定,...

    java定时任务的实现方式

    首先,Java基础定时任务实现主要有三种方式: 1. 创建一个Thread并让它在while循环中运行,利用Thread.sleep()方法来模拟定时任务。这种方式简单易懂,但不推荐用于生产环境,因为它不够灵活,且容易造成资源浪费,...

    Java定时器Timer简述.pdf

    Java定时器Timer是Java语言中用于在线程中定时执行任务的工具类,它提供了调度任务的能力,可以在指定的延迟后或者按照固定的周期执行任务。Timer类位于`java.util`包中,是线程安全的,但并不保证实时执行,这意味...

    多线程的讲解

    Quartz 是一个强大的 Java 任务调度框架,可以实现复杂的定时任务需求。例如,可以通过配置让它在每周一至周五的特定时间触发任务。Quartz 提供了丰富的 API 和调度策略,适用于企业级应用。 ### 三、传统线程互斥...

    详解SpringBoot定时任务说明

    其中,Scheduled是SpringBoot提供的一种轻量级的定时任务实现方式,使用起来简单且高效。 一、定时任务实现方式 1. 使用Java自带的java.util.Timer类 Java自带的java.util.Timer类允许你调度一个java.util....

    Java定时器Timer简述

    - 如果你不再需要Timer,记得调用`timer.cancel()`来取消所有未来的调度任务并终止Timer线程,防止内存泄漏。 - 当Timer的`TimerTask`任务抛出未捕获的异常时,Timer线程将停止执行所有后续的任务。因此,建议在`...

    Spring.3.x企业应用开发实战(完整版).part2

    9.2.4 与Thread同步机制的比较 9.2.5 Spring使用ThreadLocal解决线程安全问题 9.3 Spring对事务管理的支持 9.3.1 事务管理关键抽象 9.3.2 Spring的事务管理器实现类 9.3.3 事务同步管理器 9.3.4 事务传播行为 9.4 ...

    Spring3.x企业应用开发实战(完整版) part1

    9.2.4 与Thread同步机制的比较 9.2.5 Spring使用ThreadLocal解决线程安全问题 9.3 Spring对事务管理的支持 9.3.1 事务管理关键抽象 9.3.2 Spring的事务管理器实现类 9.3.3 事务同步管理器 9.3.4 事务传播行为 9.4 ...

    post-bumper:以特定时间间隔不断冲击给定帖子的服务

    3. **计划程序库**:例如,`Quartz Scheduler`是一个强大的开源任务调度库,可以用于复杂的调度任务,包括周期性的执行。 4. **网络编程**:服务需要与目标帖子所在的服务器进行交互,可能涉及HTTP或HTTPS请求,这...

Global site tag (gtag.js) - Google Analytics