Spring定时器

定时器有两种实现形式:

(1)借助java.util.Timer来实现。

(2)OpenSymphony社区提供的Quartz来实现


Timer

使用Timer方式实现定时器,原理简单、实现方便,在执行简单重复任务时比较方便。但其无法知道系统在几点几分执行,且必须继承指定类

利用Timer开发定时任务分两步:

  • (1)创建定时任务类
  • (2)运行定时任务

创建定时任务类

import java.util.TimerTask;
public class MainTask extends TimerTask {
    ......
    public void run() {
        //执行的定时器任务
    }
}

运行定时任务

运行定时任务分两种方式:程序直接启动;Web监听方式。

(1)程序直接启动

public class Main {
    public void run() {
        //执行定时器任务
        Timer timer = new Timer();
        timer.schedule(new MainTask(),0,1*1000);//参数(定时任务类,首次启动时间,间隔时间)
    }
}

(2)Web监听方式

public class BindLoader implements ServletContextListener {
    private Timer timer = null;
    //监视器初始化时执行事件
    public void contextInitialized(ServletContextEvent sce) {
        Timer timer = new Timer();
        timer.schedule(new MainTask(),0,1*1000);//参数(定时任务类,首次启动时间,间隔时间)
    }
    //监视器停止时执行事件
    public void contextDextroyed(ServletContextEvent sce) {      
        timer.cancel();
    }
}

创建监听类后,在web.xml中注册该监听类:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    ......
    <listener>
        <listener-class>
            com.gc.action.BindLoader
        </listener-class>
    </listener>
    ......
</web-app>

Quartz

使用Quartz方式实现定时器,可以方便、清楚地设定定时器启动地时间,定时器参数比较灵活,且容易实现各种复杂的定时任务。不足之处是实现指定接口,且需要加载相应的框架。在实际应用中,应用比较广泛

利用Quartz开发定时任务分两步:

  • (1)创建定时任务类
  • (2)运行定时任务

创建定时任务类

public class MainTask implements Job {
    ......
    public void execute(JobExecutionContext context) throws JobExecutionException{
        //执行的定时器任务
    }
}

运行定时任务

运行定时任务分两种方式:程序直接启动;Web监听方式。

(1)程序直接启动

public class MainShedule {
    private static Sheduler sched; 
    public static void run() throws Exception {
        //创建任务
        JobBetail jobDetail = new JobDetail("myJob",sched.DEFAULT_GROUP,MainTask.class);
        //创建任务计划
        CronTrigger trigger = new CronTrigger("myTrigger","test","0/10 * * * * ?");
        //调度任务
        sched = new org.quartz.impl.StdSchedulerFactory().getScheduler();
        sched.scheduleJob(jobDetail,trigger);
        sched.start();
    }
    public static void stop() throws Exception {
        sched.shutdown();
    }
}
  • "0 0 12 * * ?":表示每天中午12点触发;
  • "0 15 10 * * ? 2006":表示2006年每天上午10:15触发;
  • "0 10,44 14 ? 3 WED":表示每年三月的星期三的下午2:10和2:44触发;
public class Main {
    public void run() {
        //执行定时器任务
        MainShedule.run();
    }
}

(2)Web监听方式

public class BindLoader implements ServletContextListener {
    //监视器初始化时执行事件
    public void contextInitialized(ServletContextEvent sce) {
        MainShedule.run();
    }
    //监视器停止时执行事件
    public void contextDextroyed(ServletContextEvent sce) {      
        MainShedule.stop();
    }
}

创建监听类后,在web.xml中注册该监听类:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    ......
    <listener>
        <listener-class>
            com.gc.action.BindLoader
        </listener-class>
    </listener>
    ......
</web-app>

Spring中使用Timer实现定时器

import java.util.TimerTask;
public class MainTask extends TimerTask {
    ......
    public void run() {
        //执行的定时器任务
    }
}
<!--TimerConfig.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<!--注册定时执行实体-->
	<bean id="mainTask" class="com.gc.action.MainTask"/>
	<!--注册定时器信息-->
	<bean id="stTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
		<!--首次执行任务前需等待2秒-->
		<property name="delay">
			<value>2000</value>
		</property>
		<!--任务执行的周期为4秒-->
		<property name="period">
			<value>4000</value>
		</property>
		<!--具体的执行任务-->
		<property name="timerTask">
			<ref local="mainTask"/>
		</property>
	</bean>
	<!--配置任务调度器-->
	<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
		<!--注入定时器列表-->
		<property name="scheduledTimerTasks">
			<list>
				<ref local="stTask"/>
			</list>
		</property>		
	</bean>
</beans>
<!--web.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    ......
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-name>/WEB-INF/TimerConfig.xml</param-name>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    ......
</web-app>

Spring中使用Quartz实现定时器

public class MainTask {
    ......
    public void execute() {
        //执行的定时器任务
    }
}
<!--TimerConfig.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<!--注册定时执行实体-->
	<bean id="mainTask" class="com.gc.action.MainTask"/>
	<!--注册定时器信息-->
	<bean id="mainJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<!--指定要执行的定时任务类-->
		<property name="targetObject">
			<ref local="mainTask"/>
		</property>
		<!--指定要执行的任务方法名称-->
		<property name="targetMethod">
			<value>execute</value>
		</property>
	</bean>
	<!--配置任务调度器-->
	<bean id="timeTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
		<!--声明要运行的实体-->
		<property name="jobDetail">
			<ref local="mainJob"/>
		</property>	
        <!--设置要运行的时间-->
		<property name="cronExpression">
			<value>12,23 * * * * ?</value>
		</property>		
	</bean>
    <!--注册定时器-->
    <bean id="sfb" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<!--注入定时器实体-->
		<property name="triggers">
			<list>
                <ref local="timeTrigger"/>
            </list>
		</property>		
	</bean>
</beans>
<!--web.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    ......
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-name>/WEB-INF/TimerConfig.xml</param-name>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    ......
</web-app>

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥羊汤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值