quartz入门

1.maven配置:

        <!--quartz -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.1.7</version>
        </dependency>

 

 

2.编写程序(实现每两秒打印当前日期并且不停的打印)

  • 实现job类(HelloJob.java)
package cn.qlq.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.TriggerKey;

public class HelloJob implements Job {
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //打印当前的时间
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println("current time is:"+sf.format(date));
        System.out.println("hello world");
        // 编写具体的业务逻辑
    }
}

 

 

  • HelloScheduler .java开启任务调度
package cn.qlq.quartz;

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

import java.util.GregorianCalendar;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.calendar.AnnualCalendar;

public class HelloScheduler {

    public static void main(String[] args) {
        try {
            //1. 创建一个JodDetail实例 将该实例与Hello job class绑定    (链式写法XX.XX.XX)
            JobDetail jobDetail = newJob(HelloJob.class) // 定义Job类为HelloQuartz类,这是真正的执行逻辑所在
                    .withIdentity("myJob","group1") // 定义name/group
                    .build();//2. 定义一个Trigger,定义该job立即执行,并且每两秒钟执行一次,直到永远
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1")// 定义名字和组
                    .startNow()//现在开始
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever())
                    .build();
            
            //3. 创建scheduler
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

            //4. 将trigger和jobdetail加入这个调度
            scheduler.scheduleJob(jobDetail, trigger);

            //5. 启动scheduler
            scheduler.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

注意:创建Scheduler的方式也可以改为:

            // 3. 创建scheduler
            SchedulerFactory sfact = new StdSchedulerFactory();
            Scheduler scheduler = sfact.getScheduler();

 

 

 

运行结果:

 

posted @ 2018-04-04 20:56  QiaoZhi  阅读(430)  评论(2编辑  收藏  举报