參考:http://www.javashuo.com/article/p-nqmlkfay-bq.htmljava
<!--用到Me--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
@Configuration public class ScheduledConfiguration { /** * 定義JobDetail * @param schedledTasks * @return */ @Bean public MethodInvokingJobDetailFactoryBean datailFactoryBean(SchedledTasks schedledTasks){ MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean(); //設置對應的job對象 bean.setTargetObject(schedledTasks); //設置schedledTasks對應的方法名 bean.setTargetMethod("excute"); return bean; } /** * 定義trigger * @param jobDetail * @return */ @Bean public CronTriggerFactoryBean cronTriggerFactoryBean(MethodInvokingJobDetailFactoryBean jobDetail){ CronTriggerFactoryBean trigger = new CronTriggerFactoryBean(); trigger.setJobDetail(jobDetail.getObject()); trigger.setCronExpression("0/5 * * ? * *");//每5秒執行一次 return trigger; } /** * 定義scheduler * @param trigger * @return */ @Bean public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean trigger){ SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); scheduler.setTriggers(trigger.getObject()); return scheduler; } }
@Component public class SchedledTasks { public void excute(){ //執行任務 System.out.println("excute == " + new Date()); } }