首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Spring 定时任务-一

2012-10-14 
Spring 定时任务-1先上一个很简单的例子import java.util.Timerimport java.util.TimerTaskpublic class

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("|");       }   } 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
再上一简单例子(Web):
//配置文件
<?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("异常!");}}}}



//bean
package com.oyp.job;public class BeanTest {   void method() {   System.out.println("Fuck!");   }}



热点排行