quartz 立即執行+定時+防止併發+監聽Job是否執行狀態
阿新 • • 發佈:2019-02-16
這文章沒有新手教程,只有個人一些筆記,新手請下載附件教程:
SimpleRun:
package cn.wa8.qweb.extract.quartz; import java.util.Date; import org.quartz.CronTrigger; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.impl.StdScheduler; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import cn.wa8.qweb.extract.action.Extract2DB; public class SimpleRun { private static Logger log = LoggerFactory.getLogger(SimpleRun.class); public void run() throws Exception { SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory(); Scheduler sched = schedFact.getScheduler(); JobDetail jobDetail = new JobDetail("myJob",null,SimpleJob.class); SimpleTrigger trigger = new SimpleTrigger("myTrigger", null, new Date(), null, SimpleTrigger.REPEAT_INDEFINITELY, 30L * 1000L); sched.scheduleJob(jobDetail, trigger); //sched.addJobListener(new MyTriggerListener()); SimpleJob.preDate = new Date(); sched.start(); System.out.println("starting"); /** * state的值代表該任務觸發器的狀態: STATE_BLOCKED 4 // 執行 STATE_COMPLETE 2 //完成那一刻,不過一般不用這個判斷Job狀態 STATE_ERROR 3 // 錯誤 STATE_NONE -1 //未知 STATE_NORMAL 0 //正常無任務,用這個判斷Job是否在執行 STATE_PAUSED 1 //暫停狀態 */ while (true){ if(4 == sched.getTriggerState("myTrigger", null)){ System.out.println("running"); }else if(0 == sched.getTriggerState("myTrigger", null)){ System.out.println("ending"); }else { System.out.println("error state:"+sched.getTriggerState("myTrigger", null)); } try { Thread.sleep(5*1000); } catch (Exception e) { // TODO: handle exception } } } public static void main(String[] args) { SimpleRun simpleRun = new SimpleRun(); try { simpleRun.run(); } catch (Exception e) { e.printStackTrace(); } } }
Simple Job:
import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.wa8.qweb.extract.action.Extract2DB; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.StatefulJob; /*Extract2DB extract2db = new Extract2DB(); extract2db.CommonBaseExtract();*/ public class SimpleJob implements StatefulJob{ public static Date preDate ; public void execute(JobExecutionContext arg0) throws JobExecutionException { System.out.println("into Job"); Date currentDate = new Date(); Long s = (currentDate.getTime()-preDate.getTime())/1000; try { Thread.sleep(10*1000); } catch (Exception e) { e.printStackTrace(); } System.out.println(s); System.out.println("leave Job:"+Thread.currentThread().toString()); preDate =currentDate; } }