java版定時任務quartz【石英鐘】
阿新 • • 發佈:2018-12-12
我的疑問?
-
怎麼實現job和trigger的可配置呢?
例如我想執行一個類,但是呢?如果這個類定義了,是不是就固定了?除非可以額外傳引數,google下真的可以傳引數。【How to pass instance variables into Quartz job?】 -
怎麼實現任務的終止呢?
不是排程器的終止,是任務的終止。
Try make your job implements org.quartz.InterruptableJob, and then you may call org.quartz.Scheduler.interrupt(JobKey).
// quartz.properties org.quartz.scheduler.instanceName = MyScheduler org.quartz.threadPool.threadCount = 3 org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
package com.qlkj; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class HelloJob implements Job { @Override public void execute(JobExecutionContext var1) throws JobExecutionException{ System.out.println("hello world"); System.out.println(System.currentTimeMillis()); } }
package com.qlkj; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import static org.quartz.JobBuilder.*; import static org.quartz.TriggerBuilder.*; import static org.quartz.SimpleScheduleBuilder.*; public class QuartzTest { public static void main(String[] args) { try { // Grab the Scheduler instance from the Factory Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // and start it off scheduler.start(); // define the job and tie it to our HelloJob class JobDetail job = newJob(HelloJob.class) .withIdentity("job1", "group1") .build(); // Trigger the job to run now, and then repeat every 40 seconds Trigger trigger = newTrigger() .withIdentity("trigger1", "group1") .startNow() .withSchedule(simpleSchedule() .withIntervalInSeconds(5) .repeatForever()) .build(); // Tell quartz to schedule the job using our trigger scheduler.scheduleJob(job, trigger); // scheduler.shutdown(); } catch (SchedulerException se) { se.printStackTrace(); } } }
CronTrigger
CronTrigger使用cron-expressions進行任務觸發,cron表示式從左到右依次代表著
Seconds
Minutes
Hours
Day-of-Month
Month
Day-of-Week
Year (optional field)
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(cronSchedule("0 0/2 8-17 * * ?"))
.forJob("myJob", "group1")
.build();