近期项目中有用到Quartz,故现在学习Quartz以满足工作需求。

  这里列出几个Quartz的Demo,循序渐进的学习Quartz,找出最方便好用的使用方式。

  方式一:Maven+Quartz本身Api,实现每隔两秒打印HelloWorld

    1、在pom.xml中加入Quartz的依赖:

    
            
org.quartz-scheduler
        
quartz
        
2.2.3
    

   2、写出继承了Job的实现类

    package com.aweiyo.demo.helloQuartz;        import java.text.SimpleDateFormat;    import java.util.Date;    import org.quartz.Job;    import org.quartz.JobExecutionContext;    import org.quartz.JobExecutionException;        public class HelloJob implements Job {        public void execute(JobExecutionContext arg0) throws JobExecutionException {    Date date = new Date();    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");    System.err.println("当前时间为:==========" + sf.format(date));    System.out.println("hello quartz...");    }        }

    3、写出Scheduler。

            

    package com.aweiyo.demo.helloQuartz;            import org.quartz.JobBuilder;    import org.quartz.JobDetail;    import org.quartz.Scheduler;    import org.quartz.SchedulerException;    import org.quartz.SchedulerFactory;    import org.quartz.SimpleScheduleBuilder;    import org.quartz.Trigger;    import org.quartz.TriggerBuilder;    import org.quartz.impl.StdSchedulerFactory;    public class HelloScheduler {    public static void main(String[] args) throws SchedulerException {    // 创建JobDetail实例,将该实例与HelloJob绑定    JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)    .withIdentity("aweiyoJob", "group1").build();    // 创建一个Trigger实例    Trigger trigger = TriggerBuilder.newTrigger()    .withIdentity("aweiyoTrigger", "group1").startNow()    .withSchedule(SimpleScheduleBuilder.simpleSchedule()    .withIntervalInSeconds(2).repeatForever())    .build();    // 创建Scheduler实例    SchedulerFactory sfact = new StdSchedulerFactory();    Scheduler scheduler = sfact.getScheduler();    scheduler.start();    scheduler.scheduleJob(jobDetail, trigger);    }    }