1.這裏的例子使用的是quartz-all-2.1.7.jar,這個jar包依賴log4j-1.2.16.jar,slf4j-api-1.6.1.jar,slf4j-log4j12-1.6.1.jar java
2.上代碼 api
package study.quartz; import org.quartz.*; import org.quartz.impl.JobDetailImpl; import org.quartz.impl.StdSchedulerFactory; /** * Created with IntelliJ IDEA. * User: gl * Date: 13-6-5 * Time: 下午7:40 * ClassDesc: * To change this template use File | Settings | File Templates. */ public class TestQuartz { public static void main(String[] args) throws SchedulerException { SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); JobDetail jobDetail = JobBuilder.newJob() .ofType(HelloJob.class) .usingJobData("Test1","Quartz") .withIdentity("Test1","Group1") .build();//經過JobBuilder構建JobDetailImpl 實例,也能夠直接new JobDetailImpl Trigger trigger = TriggerBuilder.newTrigger() .withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * * * ?")) .forJob("Test1","Group1") //Trigger找到對應的名稱爲Test1組爲Group1的Job,若是不存在則會在執行scheduler.scheduleJob(jobDetail,trigger);報錯 .build();//經過TriggerBuilder構建CronTriggerImpl實例,也能夠直接new CronTriggerImpl scheduler.scheduleJob(jobDetail,trigger);//任務每3秒觸發一次 scheduler.start(); } }
package study.quartz; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * Created with IntelliJ IDEA. * User: gl * Date: 13-6-6 * Time: 上午9:57 * ClassDesc: * To change this template use File | Settings | File Templates. */ public class HelloJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); String a = (String)jobDataMap.get("Test1"); System.out.println("Hello " + a); } }
任務的定義比較簡單,只須要implements Job,實現execute方法便可,觸發任務時,execute方法會執行. ide
示例定義的是一個每三秒執行一次的任務,經過TriggerBuilder構建Trigger實例,也能夠直接經過new方式構建. ui
這個示例使用的是默認的quartz配置,若是指定配置,能夠編輯一個Properties文件, this
schedulerFactory.initialize(props);//初始化指定配置
第一次發文章,不足之處請各位看客斧正,歡迎交流! spa