java+Quartz实现定时任务

1、首先:导入quartz相关的jar包,这里我用的是maven构建的项目,pom.xml文件导入如下:

  <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz</artifactId>
      <version>2.2.1</version>
  </dependency>
  <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz-jobs</artifactId>
      <version>2.2.1</version>
  </dependency>

 

2、定义要进行定时任务类(该类实现了Quartz 下的job类):

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        // TODO Auto-generated method stub
        System.out.println("开启了定时任务");

    }

}

 

3、接下来要做的就是按照定时任务的固定步骤来做即可:1:定义调度器并且开启   2:定义任务器  3:定义触发器   4 注册 

 

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzDemo {

    public static void main(String[] args) {
        try {
            new QuartzDemo().quartzTest();
        } catch (InterruptedException i) {
            i.printStackTrace();
        }
    }

    public void quartzTest() throws InterruptedException{
        try {
            //获取调度器
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();
            //创建任务器:定义任务细节
            JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("job1", "group1").build();
            ScheduleBuilder scheduleBuilder =SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever();
            //定义触发器
            Trigger trigger=TriggerBuilder.newTrigger().withIdentity("simpleTrigger", "simpleTriggerGroup")
                    .withSchedule(scheduleBuilder).startNow().build();

            //将任务和触发器注册到调度器中
            scheduler.scheduleJob(jobDetail, trigger);
            // Thread.sleep(1000*30);
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

posted @ 2018-11-28 17:27  UniqueColor  阅读(6436)  评论(0编辑  收藏  举报