quartz demo

QuartzJob 类:创建job类,实现org.quartz.job接口类,并实现execute方法。

package com.pgw.quartz;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class QuartzJob implements Job{
   public void execute(JobExecutionContext arg0) throws JobExecutionException {
      System.out.println("Hello world !!!" + new Date());
   }
}

QuartzCronTrigger 类:创建crontrigger类,继承CronTrigger类,实现 Serializable接口

package com.pgw.quartz;

import org.quartz.CronTrigger;
import java.io.Serializable;
import java.text.ParseException;

public class QuartzCronTrigger extends CronTrigger implements Serializable {
    private static final long serialVersionUID = 1L;

    public QuartzCronTrigger() {
    }

    public void setCronExpress(String corn, String name, String groupName) {
        try {
            this.setCronExpression(corn);
            this.setName(name);
            this.setGroup(groupName);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

QuartzMain 类
1、如果Scheduler没有设置名称,通过scheduler = factory.getDefaultScheduler();获取的Scheduler对象名称为DefaultQuartzScheduler。
2、Quartz可以设置一个Scheduler,然后在这个Scheduler下配置多对trigger和job度对象。

package com.pgw.quartz;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;

import org.quartz.impl.StdSchedulerFactory;


public class QuartzMain {
    public static void main(String[] args) {
        // 创建一个jobDetail对象,将Job实际业务类放入jobDetail中
        JobDetail jobDetail = new JobDetail("demo", "demo", QuartzJob.class);

        // 创建一个触发器
        CronTrigger triggers = new QuartzCronTrigger();

        try {
            // 设置触发器 名字
            triggers.setName("demo");
            // 设置触发器所属组
            triggers.setGroup("demo");
            // 设置触发时间cron表达式
            triggers.setCronExpression("10 * * * * ?");
            // 将jobDetail放入触发器中
            triggers.setJobGroup("demo");

            // 创建schedulerFactory对象
            StdSchedulerFactory factory = new StdSchedulerFactory();

            Scheduler scheduler = factory.getDefaultScheduler();
            // Register the JobDetail and Trigger
            scheduler.scheduleJob(jobDetail, triggers);

            // 挂起定时线程
            scheduler.start();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

 

发表评论