Java定时器和Quartz使用


一、Java普通自定义定时器

 1 /**
 2  *  自定义一个定时器
 3  * @author lw
 4  */
 5 public class MyTimer extends Thread{
 6 
 7     private Long time ;
 8 
 9     public MyTimer(Long time) {
10         this.time = time;
11     }
12 
13     @Override
14     public void run() {
15         while(true){
16             try {
17                 Thread.sleep(time);
18             } catch (InterruptedException e) {
19                 e.printStackTrace();
20             }
21             send();
22         }
23     }
24     /**
25      *  开始执行任务
26      */
27     public void execute(){
28         this.start();
29     }
30 
31     /**
32      *  定时任务
33      */
34     private void send() {
35         System.out.println("任务执行了:" + new Date());
36     }
37 
38     public static void main(String[] args) {
39         MyTimer myTimer = new MyTimer(2000L) ;
40         myTimer.execute();
41     }
42 
43 }

 

输出内容:

 1 任务执行了:Tue Nov 13 10:10:02 CST 2018
 2 任务执行了:Tue Nov 13 10:10:04 CST 2018
 3 任务执行了:Tue Nov 13 10:10:06 CST 2018
 4 任务执行了:Tue Nov 13 10:10:08 CST 2018
 5 任务执行了:Tue Nov 13 10:10:10 CST 2018
 6 任务执行了:Tue Nov 13 10:10:12 CST 2018
 7 任务执行了:Tue Nov 13 10:10:14 CST 2018
 8 任务执行了:Tue Nov 13 10:10:16 CST 2018
 9 任务执行了:Tue Nov 13 10:10:18 CST 2018
10 任务执行了:Tue Nov 13 10:10:20 CST 2018

 

二、使用Java   Timer类

 1 public class TimerTest {
 2 
 3     public static void main(String[] args) {
 4         Timer timer = new Timer();
 5         // 5s后执行
 6         // timer.schedule(new MyTask(), 5000);
 7         // 马上执行任务,每隔1000执行一次
 8         timer.scheduleAtFixedRate(new MyTask(), new Date(), 1000);
 9     }
10 
11 }
12 
13 // 定时任务,这是一个线程
14 class MyTask extends TimerTask {
15     @Override
16     public void run() {
17         System.out.println("task execute ");
18     }
19 }

Timer也是基于线程来实现的。

三、Quartz框架

Quartz是一个完全由Java编写的开源作业调度框架,为在Java应用程序中进行作业调度提供了简单却强大的机制。Quartz允许开发人员根据时间间隔来调度作业。它实现了作业和触发器的多对多的关系,还能把多个作业与不同的触发器关联。

使用如下:

创建job

1 public class HelloJob implements Job{
2 
3     public void execute(JobExecutionContext context) throws JobExecutionException {
4         JobDetail detail = context.getJobDetail(); 
5         String name = detail.getJobDataMap().getString("name");
6         System.out.println("say hello " + name );
7     }
8 
9 }

 

测试

 1 public class QuartzTest {
 2 
 3     public static void main(String[] args) throws InterruptedException {
 4 
 5         // 创建工厂
 6         SchedulerFactory schedulerfactory = new StdSchedulerFactory();
 7         Scheduler scheduler = null;
 8         try {
 9             // 通过schedulerFactory获取一个调度器
10             scheduler = schedulerfactory.getScheduler();
11 
12             // 指明job的名称,所在组的名称,以及绑定job类
13             JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("JobName", "JobGroupName")
14                     .usingJobData("name", "quartz").build();
15             // 定义触发的条件
16             Trigger trigger = TriggerBuilder.newTrigger().withIdentity("CronTrigger1", "CronTriggerGroup")
17                     .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever())
18                     .startNow().build();
19 
20             // 把作业和触发器注册到任务调度中
21             scheduler.scheduleJob(job, trigger);
22 
23             // 启动调度
24             scheduler.start();
25 
26             Thread.sleep(10000);
27 
28             // 停止调度
29             scheduler.shutdown();
30 
31         } catch (SchedulerException e) {
32             e.printStackTrace();
33         }
34 
35     }
36 }

步骤:

  1. 创建job
  2. 创建工厂,获取调度器
  3. 使用JobBuilder通过job生成jobDetail,可以传递数据
  4. 通过TriggerBuilder创建Trigger,可以设置时间
  5. 通过调度器注册ob和trigger
  6. 启动调度

四、Quarts 和 Spring整合

创建job

1 public class MailJob {
2 
3     private void send() {
4         System.out.println("发送邮件了:" + new Date()); 
5     }
6 }

 

配置

 1 <description>Quartz配置文件</description>
 2     <!-- 定义一个job -->
 3     <bean id="mailJob" class="com.lw.jk.job.MailJob"></bean>
 4     <!-- 定义一个 MethodInvokingJobDetailFactoryBean-->
 5     <bean id="methodInvokingJobDetailFactoryBean" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
 6         <property name="targetObject" ref="mailJob"></property>
 7         <property name="targetMethod" value="send"></property>
 8     </bean>
 9     <!-- 指定时间 -->
10     <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
11         <property name="jobDetail" ref="methodInvokingJobDetailFactoryBean"></property>
12         <property name="cronExpression" value="0/10 * * * * ? *"></property>
13     </bean> 
14 
15     <!-- 指定调度器 -->
16     <bean id="schedule" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
17         <property name="triggers">
18             <list>
19                 <ref bean="cronTrigger"/>
20             </list>
21         </property>
22     </bean>

 

输出结果:

1 发送邮件了:Sat Apr 15 16:12:00 CST 2017
2 发送邮件了:Sat Apr 15 16:12:10 CST 2017

 

四、spring 自带的定时任务:spring-task

spring 自身的spring-task 不依赖任何的第三方框架,实现方式也很简单:

这里需要做的就是在xml文件中的引入task命名空间,以便后续标签中的使用:

xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task 
 http://www.springframework.org/schema/task/spring-task-3.2.xsd

1:定义任务类:

1 public class TaskJob {
2 
3     public void springJob(){
4         System.out.println("spring 自身的定时任务");
5     }
6 }

2:在xml配置文件中配置定时job:

1    <!--配置任务类-->
2     <bean id="beanA" class="bz.beppe.javase.TaskJob"></bean>  
3     <!--定义触发类和触发方式-->
4     <task:scheduled-tasks scheduler="myScheduler">
5         <task:scheduled ref="beanA" method="springJob" fixed-rate="5000"/>
6     </task:scheduled-tasks>
7 
8     <task:scheduler id="myScheduler" pool-size="10"/>

经过这样的配置后在在开启这个定时任务的spring容器后就会开始相应的定时job。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM