Spring 定时任务-1
先上一个很简单的例子
import java.util.Timer;import java.util.TimerTask;public class Test extends TimerTask { public static void main(String[] args) { Timer t=new Timer(); t.schedule(new Test(),0,1000); } public void run() { System.out.println("|"); } } <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="schedulerFactory"/></list></property><property name="applicationContextSchedulerContextKey"><value>applicationContext</value> </property> </bean> <bean id="SendMessageJobInThreeM" ref="SendMessageJob" /><property name="cronExpression" value="/10 * * * * ? " /> </bean> <bean id="SendMessageJob" value="com.oyp.job.QuartTest" /> </bean> <bean id = "beanTest" class = "com.oyp.job.BeanTest" > </bean></beans>
package com.oyp.job;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.springframework.context.ApplicationContext;/** * @author oyp mail:oyprunner@gmail.com */public class QuartTest implements Job{public void execute(JobExecutionContext context) throws JobExecutionException {System.out.println("定时任务开始!");Scheduler sch = (Scheduler) context.getScheduler();String jobname = context.getJobDetail().getName();String jobgroup = context.getJobDetail().getGroup();try {ApplicationContext appCtx = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");sch.pauseJob(jobname, jobgroup);BeanTest bt = (BeanTest)appCtx.getBean("beanTest");bt.method();} catch (SchedulerException e) {e.printStackTrace();} finally {try {sch.resumeJob(jobname, jobgroup);System.out.println("定时任务结束!");} catch (SchedulerException e) {System.out.println("异常!");}}}}package com.oyp.job;public class BeanTest { void method() { System.out.println("Fuck!"); }}