java web开发常用5种自启动定时任务方式及区别

本文介绍了Spring中四种定时任务的实现方式:MethodInvoke、继承QuartzJobBean、实现Job接口及TimerTask,并展示了如何在Spring配置文件中进行具体配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     首先把用到的四个类贴上来

   

public class CronTriggerTest
{
    /**
     * 以method invoke方式执行定时任务
     */
    public void sayHello()
    {
        System.out.println("方法1:methodinvoke start");
    }

}

public class JobQuartzTest extends QuartzJobBean
{
    private int timeout;

    public int getTimeout()
    {
        return timeout;
    }

    public void setTimeout(int timeout)
    {
        this.timeout = timeout;
    }

    /**
     * 以extends QuartzJobBean方式执行定时任务,企业开发中常用,因为可以注入上面timout,service等参数
     */
    @Override
    protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException
    {
        System.out.println("方法2:QuartzJobBean start;timerout value="+timeout);
    }

}

public class jobTest implements Job
{
    private int timeout;

    public int getTimeout()
    {
        return timeout;
    }

    public void setTimeout(int timeout)
    {
        this.timeout = timeout;
    }

    /**
     * 以implements job方式执行定时任务,不支持上面的属性注入,与implents quartzJobBean就这一点差别
     */
    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException
    {
        System.out.println("方法3: job test timout=" + timeout);
    }

}

public class TimerTaskTest extends TimerTask
{

    /**
     * 最简单的以timertask定时任务方式
     */
    @Override
    public void run()
    {
     System.out.println("方法4:timer task start");
    }

}

   我在spring配置文件中配置上面所有的

  

<!-- quartz定时任务  start-->

	<!-- 作业使用继承QuartzJobBean的方式  start -->
	<bean name="job1"
		class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass" value="com.chenjun.JobQuartzTest" />
		<property name="jobDataAsMap">
			<map>
				<entry key="timeout" value="10" />
			</map>
		</property>
	</bean>


	<bean id="jobQuartzTest"
		class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail">
			<ref bean="job1" />
		</property>
		<property name="cronExpression" value="0 0/2 * * * ?" />
	</bean>
	<!-- 作业使用继承QuartzJobBean的方式 end -->

	<!-- 作业使用implements job的方式  start -->
	<bean name="job2"
		class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass" value="com.chenjun.jobTest" />
		<property name="jobDataAsMap"><!-- 注意这里job不支持这个属性的注入 -->
			<map>
				<entry key="timeout" value="20" />
			</map>
		</property>
	</bean>


	<bean id="jobQuartzTest2"
		class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail">
			<ref bean="job2" />
		</property>
		<property name="cronExpression" value="0 0/2 * * * ?" />
	</bean>
	<!-- 作业使用继承QuartzJobBean的方式 end -->


	<!-- 以methodinvoke方式 start -->
	<bean id="helloJobBean" class="com.chenjun.CronTriggerTest"></bean>
	<bean id="helloJob"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject">
			<ref bean="helloJobBean" />
		</property>
		<property name="targetMethod">
			<value>sayHello</value>
		</property>
	</bean>

	<bean id="helloJobTrigger"
		class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail">
			<ref bean="helloJob" />
		</property>
		<property name="cronExpression" value="0 0/2 * * * ?" />
	</bean>
	<!-- 以methodinvoke方式 end -->

	<!-- 与上面一样,也可配置,相当于timer task了,工作中常用上面一种
		<bean id="taskTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
		<property name="jobDetail" ref="jobDetail" />
		<property name="startDelay" value="10000" />
		<property name="repeatInterval" value="60000" />
		</bean> -->


	<!-- 以上仅仅是定义定时任务,并未在服务器加载时执行 -->

	<!-- 总的定时任务执行 -->
	<bean id="schedulerFactoryBean"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list><!-- 执行定时任务 -->
				<!-- 以methodinoke方式 -->
				<ref bean="helloJobTrigger" />

				<!--以extent quartzJobBean方式  -->
				<ref bean="jobQuartzTest" />

				<!--以implement Job方式  -->
				<ref bean="jobQuartzTest2" />
			</list>
		</property>
	</bean>
	<!-- quartz定时任务 end  -->



	<!-- timer task start -->
	<bean id="timerTassTest" class="com.chenjun.TimerTaskTest"></bean>

	<bean id="hellotask"
		class="org.springframework.scheduling.timer.ScheduledTimerTask">
		<property name="timerTask">
			<ref bean="timerTassTest" />
		</property>
		<property name="delay"><!-- tomcat容器启动1秒后执行 -->
			<value>1000</value>
		</property>
		<property name="period"><!-- 之后每隔2分钟执行一次 -->
			<value>120000</value>
		</property>
	</bean>

	<!-- 总的定时任务执行list -->
	<bean id="timer"
		class="org.springframework.scheduling.timer.TimerFactoryBean">
		<property name="scheduledTimerTasks">
			<list>
				<ref local="hellotask" />
			</list>
		</property>
	</bean>
	<!-- timer task end -->

  执行结果:

 

方法1:methodinvoke start
方法2:QuartzJobBean start;timerout value=10
方法3: job test timout=0
方法4:timer task start

另外还有一种是通过在web.xml中配置的,如下:

public class webForTimerTask extends TimerTask
{
    private ServletContext context = null;

    @Override
    public void run()
    {
        System.out.println("web.xml 中执行timer task");
    }

    public webForTimerTask(ServletContext context)
    {
        this.context = context;
    }

}

 
public class WebTimerTaskTestListener implements ServletContextListener
{
    private Timer timer = null;

    public Timer getTimer()
    {
        return timer;
    }

    public void setTimer(Timer timer)
    {
        this.timer = timer;
    }

    @Override
    public void contextDestroyed(ServletContextEvent event)
    {
        timer.cancel();
        event.getServletContext().log("定时器销毁");
    }

    @Override
    public void contextInitialized(ServletContextEvent event)
    {
        timer = new Timer(true);
        event.getServletContext().log("定时器已启动");// 添加日志,可在tomcat日志中查看到
        timer.schedule(new webForTimerTask(event.getServletContext()), 0, 5 * 1000);// 调用
        // exportHistoryBean,0表示任务无延迟,5*1000表示每隔5秒执行任务
    }

}

web.xml中加入上面的监听类

<!-- 定时任务监听 -->
	  	<listener>
		<listener-class>
			com.chenjun.WebTimerTaskTestListener
		</listener-class>
	</listener>

  执行结果:

2014-12-27 22:17:01 org.apache.jk.server.JkMain start
信息: Jk running ID=0 time=0/16  config=null
2014-12-27 22:17:01 org.apache.catalina.startup.Catalina start
信息: Server startup in 7308 ms
web.xml 中执行timer task
web.xml 中执行timer task
web.xml 中执行timer task

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值