My Octopress Blog

A blogging framework for hackers.

Quartz学习

| Comments

quartz是用于定时任务的组件, 可以用在j2se,j2ee. 在quartz里面,主要有以下核心组件.

  • Job, 这是只有一个excute()方法的接口,任务代码写在这里.

  • JobDetail, 这是用于实例化Job的类,在quartz里面,把Job和配置信息分开,是一大特色.比如在JobDetail里面,可以使用JobDataMap存放Job的运行状态. 用JobBuilder实例JobDetail.

  • Trigger, 一般和Job绑定在一起,定义Job的触发时间.使用TriggerBuilder实例Trigger.

  • Scheduler负责整个定时任务跑起来,通过Scheduler sche = StdSchedulerFactory.getDefaultScheduler();实例化,使用sche.start()开始任务,sche.shutdow()结束任务.

下面是基础的示例代码

一个简单的任务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;

public class HelloJob implements Job {

  @Override
  public void execute(JobExecutionContext arg0) throws JobExecutionException {
      JobKey key = arg0.getJobDetail().getKey();获取该job的唯一标识 name+group
      
      JobDataMap dataMap = arg0.getJobDetail().getJobDataMap();
      String jobSays = dataMap.getString("jobSays");
      float myFloatValue = dataMap.getFloat("myFloatValue");
      System.err.println("Instance " + key + "says: " + jobSays + ", and val is: " + myFloatValue);
      
  }

}

在上面的代码中,先定义一个简单的Job,然后能过JobExecutionContext这个上下文类,可以获得job时,绑定的一些参数和状态.

简单的任务执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;

public class SimpleJob {

    public static void main(String[] args) {

        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").usingJobData("jobSays", "Hello World!").usingJobData("myFloatValue", 3.141f).build();
            Trigger trigger = newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(simpleSchedule().withIntervalInSeconds(10).repeatSecondlyForTotalCount(5, 10)).build();


            scheduler.start();
            scheduler.scheduleJob(job, trigger);
            Thread.sleep(60000);
            scheduler.shutdown();

        } catch (SchedulerException se) {
            se.printStackTrace();
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
    }
}

上面代码中,示例如何创建JobDetial, Trigger, Scheduer.如何使用JobDataMap

Comments