当前位置: 移动技术网 > IT编程>开发语言>Java > sping MVC 定时任务的设置

sping MVC 定时任务的设置

2020年01月06日  | 移动技术网IT编程  | 我要评论

  项目中用到了定时任务,写一篇随笔记录一下。

  首先在spring的配置文件applicationcontext.xml文件的beans标签中添加

xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task-4.1.xsd

  目前我了解的有两种方式使用定时任务:

  1.在配置文件中声明定时任务的调用

  先在applicationcontext.xml文件中声明调用的bean

<bean id="quartzcontroller" class="com.bizdata.common.socket.web.resource.quartztaskcontroller"></bean>

  调用的java方法及代码如下

import java.text.simpledateformat;
import java.util.date;

import org.springframework.stereotype.controller;

@controller
public class quartztaskcontroller {
    
    public void systime(){
        simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
        system.out.println(sdf.format(new date()));
    }

}

  然后声明调用对象和调用对象的方法

<!-- 定义调用对象和调用对象的方法 -->
    <bean id="myjobdetaila"
          class="org.springframework.scheduling.quartz.methodinvokingjobdetailfactorybean">
        <property name="targetobject" ref="quartzcontroller">  <!--执行定时类-->
        </property>
        <property name="targetmethod" value="systime"></property>   <!--执行定时的方法-->
        <property name="concurrent" value="false" />
        <!-- 是否允许任务并发执行。当值为false时,表示必须等到前一个线程处理完毕后才再启一个新的线程 -->
    </bean>
    <!-- 定义触发时间 -->
    <bean id="mytriggersa"
          class="org.springframework.scheduling.quartz.crontriggerfactorybean">
        <property name="jobdetail" ref="myjobdetaila">
        </property>
        <property name="cronexpression">
            <value>0 00 6 * * ?</value>    <!--定时时间-->
            <!--时间大小由小到大排列,从秒开始,顺序为 秒,分,时,天,月,年    *为任意 ?为无限制-->
        </property>
    </bean>

  以上即完成定时任务的设置,每天早上6点调用。

  2.通过注解调用(推荐方法,会省很多配置,方便使用)

  applicationcontext.xml文件中声明bean自动扫描:

<!-- 开启注解注入bean的支持 -->
    <context:annotation-config />
    <context:component-scan base-package="com.bizdata" />

  同时添加注解调用的配置

<task:annotation-driven/> <!-- 用定时器注解 -->

  java代码

  @scheduled(cron="0 0 22 * * ?")
    public boolean getdatacenterdata(){
        calendar calendar = calendar.getinstance();
        calendar.add(calendar.date, -1);
        return getdatacenterdata(calendar.gettime());
    }

  完成定时任务使用,每天22点调用。

  使用以上配置的注解方式调用定时任务时会打印出异常日志,但不影响使用,可以在log4j.properties文件添加一下日志等级过滤即可。

#定时器日志级别
log4j.logger.org.springframework.scheduling = info

 

  

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网