POM

  1. <dependency>
  2. <groupId>org.quartz-scheduler</groupId>
  3. <artifactId>quartz</artifactId>
  4. <version>2.2.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.quartz-scheduler</groupId>
  8. <artifactId>quartz-jobs</artifactId>
  9. <version>2.2.1</version>
  10. </dependency>

布置任务

package com.soyuan;

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

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args) {
        JobDetail job = JobBuilder.newJob(QuartzJob.class)
                .withIdentity("twxJobName", "group1").build();

        //只执行一次
        Trigger trigger1 = TriggerBuilder.newTrigger()
                .withIdentity("trigger1","group1")
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withRepeatCount(0))
                .build();

        //每天8点
        Trigger trigger2 = TriggerBuilder.newTrigger()
                .withIdentity("trigger2", "group1")
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0 8 ? * *"))
                .forJob(JobKey.jobKey("twxJobName","group1"))
                .build();

        try {

            Scheduler scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.start();
            //只执行一次
            scheduler.scheduleJob(job, trigger1);
            //每天8点执行
            scheduler.scheduleJob(trigger2);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}

具体任务

实现execute(JobExecutionContext context)方法即可

package com.soyuan;

import org.quartz.*;

/**
 * Created by twx on 2017/10/31.
 */
public class QuartzJob implements Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
      //关闭任务  
      context.getScheduler().shutdown();
    }
}