// pom.xml<dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz</artifactId><version>2.2.3</version></dependency>
// spring.xml<beanid="simpleJobDetail"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"><propertyname="targetObject"ref="myBean"/><propertyname="targetMethod"value="printMessage"/></bean><beanid="firstComplexJobDetail"class="org.springframework.scheduling.quartz.JobDetailFactoryBean"><propertyname="jobClass"value="com.imooc.springquartz.quartz.FirstScheduledJob"/><propertyname="jobDataMap"><map><entrykey="anotherBean"value-ref="anotherBean"/></map></property><propertyname="Durability"value="true"/></bean><!--距离当前时间1秒之后执行,之后每隔两秒钟执行一次--><beanid="mySimpleTrigger"class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"><propertyname="jobDetail"ref="simpleJobDetail"/><propertyname="startDelay"value="1000"/><propertyname="repeatInterval"value="2000"/></bean><!--每隔5秒钟执行一次--><beanid="myCronTrigger"class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"><propertyname="jobDetail"ref="firstComplexJobDetail"/><propertyname="cronExpression"value="0/5 * * ? * *"/></bean><beanclass="org.springframework.scheduling.quartz.SchedulerFactoryBean"><propertyname="jobDetails"><list><refbean="simpleJobDetail"/><refbean="firstComplexJobDetail"/></list></property><propertyname="triggers"><list><refbean="mySimpleTrigger"/><refbean="myCronTrigger"/></list></property></bean>
packagecom.imooc.springquartz.quartz; importjava.text.SimpleDateFormat; importjava.util.Date; importorg.springframework.stereotype.Component; @Component("myBean") publicclassMyBean { publicvoidprintMessage() { // 打印当前的执行时间,格式为2017-01-01 00:00:00Datedate=newDate(); SimpleDateFormatsf=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("MyBean Executes!"+sf.format(date)); } }
packagecom.imooc.springquartz.quartz; importorg.springframework.stereotype.Component; @Component("anotherBean") publicclassAnotherBean { publicvoidprintAnotherMessage() { System.out.println("AnotherMessage"); } }
packagecom.imooc.springquartz.quartz; importjava.text.SimpleDateFormat; importjava.util.Date; importorg.quartz.JobExecutionContext; importorg.quartz.JobExecutionException; importorg.springframework.scheduling.quartz.QuartzJobBean; publicclassFirstScheduledJobextendsQuartzJobBean { privateAnotherBeananotherBean; publicvoidsetAnotherBean(AnotherBeananotherBean) { this.anotherBean=anotherBean; } @OverrideprotectedvoidexecuteInternal(JobExecutionContextarg0) throwsJobExecutionException { Datedate=newDate(); SimpleDateFormatsf=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("FirstScheduledJob Executes!"+sf.format(date)); this.anotherBean.printAnotherMessage(); } }