Quartz 任务调度的使用

    技术2022-07-15  80

    首先需要准备作业(Job),一般实现 Job 接口的方法 execute 即可。

    public class TurnOnLight implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { int floorId = context.getJobDetail().getJobDataMap().getInt("floorId"); int areaId = context.getJobDetail().getJobDataMap().getInt("areaId"); int lightId = context.getJobDetail().getJobDataMap().getInt("lightId"); System.out.println(LocalDateTime.now()); System.out.println("打开 " + floorId + " 楼 " + areaId + " 房间的 " + lightId + " 号灯"); } }

    接下来准备 JobDetail、Trigger > 创建调度器 Scheduler > 调度作业,这样简单的作业调度就完成了。

    public class Application { public static void main(String[] args) throws Exception { JobDetail jobDetail = JobBuilder.newJob(TurnOnLight.class) .withIdentity("开灯作业", "灯光控制组") .usingJobData("floorId", 6) .usingJobData("areaId", 603) .usingJobData("lightId", 3) .build(); Trigger trigger = TriggerBuilder.newTrigger() .forJob(jobDetail) .withIdentity("间隔触发", "间隔触发组") .usingJobData("间隔时间", "5秒") .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ? 2020")) .build(); Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); } }

    StdSchedulerFactory 中有这样的代码,所以当你不需要配置的时候,不要在这些路径下添加 quartz.properties,防止读入了配置自己却还不清楚。 

    ClassLoader cl = getClass().getClassLoader(); if (cl == null) cl = findClassloader(); if (cl == null) throw new SchedulerConfigException("Unable to find a class loader on the current thread or class."); in = cl.getResourceAsStream("quartz.properties"); if (in == null) { in = cl.getResourceAsStream("/quartz.properties"); } if (in == null) { in = cl.getResourceAsStream("org/quartz/quartz.properties"); } if (in == null) { initException = new SchedulerException("Default quartz.properties not found in class path"); throw initException; }

     

    Processed: 0.011, SQL: 9