一、spring 定时任务
spring 定时任务 ,最好使用quartz 实现。下面我以spring4为例
二、实战(默认)
1、pom配置
org.quartz-scheduler quartz 1.8.4
2、bean 配置
3、定时java类, 继承 QuartzJobBean
package com.yuanmeng.spring;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.scheduling.quartz.QuartzJobBean;public class TaskDemo extends QuartzJobBean { private static int i = 0; @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { System.out.println("--------- begin ---------"); System.out.println(" i = " + i++); System.out.println("--------- end ---------"); } }
4、启动
package com.yuanmeng.spring;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.scheduling.quartz.JobDetailBean;public class Client { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/spring-timetask.xml"); org.springframework.scheduling.quartz.JobDetailBean bean = (JobDetailBean) ac.getBean("myTaskJob"); System.out.println(bean != null); }}
5、看下结果
--------- begin --------- i = 0--------- end ------------------ begin --------- i = 1--------- end ------------------ begin --------- i = 2--------- end ------------------ begin --------- i = 3--------- end ------------------ begin --------- i = 4--------- end ------------------ begin --------- i = 5--------- end ------------------ begin --------- i = 6--------- end ------------------ begin --------- i = 7--------- end ------------------ begin --------- i = 8--------- end ------------------ begin --------- i = 9--------- end ------------------ begin --------- i = 10--------- end ------------------ begin --------- i = 11--------- end ------------------ begin --------- i = 12--------- end ---------
三、实战(不继承)
1、bean 配置
2、自定义任务类
package com.yuanmeng.spring;public class TaskDemo2 { private static int i = 0; public void doIt() { System.out.println("---------doIt begin ---------"); System.out.println(" i = " + i++); System.out.println("---------doIt end ---------"); }}
3、启动
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/spring-timetask2.xml");
4、结果
---------doIt begin --------- i = 0---------doIt end ------------------doIt begin --------- i = 1---------doIt end ------------------doIt begin --------- i = 2---------doIt end ------------------doIt begin --------- i = 3---------doIt end ------------------doIt begin --------- i = 4---------doIt end ------------------doIt begin ---------