导入quartz相关jar包后,要执行任务的类须实现Job接口
package quartz; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * Created by MY on 2017/8/7. */ public class MyJob implements Job{ @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.out.println("执行任务"); } }
管理要执行的任务
package quartz; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; /** * Created by MY on 2017/8/7. */ public class QuartzTest { //任务 static JobDetail detail; //调度器 static Scheduler scheduler; static { try { scheduler=StdSchedulerFactory.getDefaultScheduler(); detail=JobBuilder.newJob(MyJob.class).withIdentity("first").build();
//first是为该任务起的名字
} catch (SchedulerException e) { e.printStackTrace(); } }; //执行规则 public static CronScheduleBuilder rule(){ //每月每天的16点到16点59分每分钟执行一次任务 ?代表的是周 return CronScheduleBuilder.cronSchedule("0/3 * 16 * * ?"); } public static void main(String[] args) { //触发规则 CronTrigger trigger=TriggerBuilder.newTrigger().startNow().withSchedule(rule()).build(); try { scheduler.scheduleJob(detail,trigger); //开始执行 scheduler.start(); JobKey first=JobKey.jobKey("first"); //暂停 /* scheduler.pauseJob(first); scheduler.resumeJob(first); scheduler.deleteJob(first);*/ //彻底停止--删除 } catch (SchedulerException e) { e.printStackTrace(); } } }