spring实现定时任务的两种方式

本文为博主原创,未经允许不得转载

       项目中要经常事项定时功能,在网上学习了下用spring的定时功能,基本有两种方式,在这里进行简单的总结,

以供后续参考,此篇只做简单的应用。

       1.在spring-servlet.xml文件中加入task的命名空间:

xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-4.0.xsd"

      然后使用task配置扫描注解

<!-- 定时任务 -->
    <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
    <task:scheduler id="qbScheduler" />  

    此时就可以直接使用@Scheduled(cron = "时间格式串"),应用该注解就可以实现定时的功能

 @Scheduled(cron = "0/5 * * * * ?")  //每隔5秒执行一次定时任务
    public void consoleInfo(){
        System.out.println("定时任务");
    }

 

第二种方法为:不使用注解实现定时任务,将定时的功能在spring配置文件中实现。

xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation=" http://www.springframework.org/schema/task   
        http://www.springframework.org/schema/task/spring-task-3.0.xsd”


<description> 定时任务 </description>
//定时注解驱动 <task:annotation-driven /> //进行定时任务的类,将其定义为一个bean <bean id="spaceStatisticsService" class="com.pojo.system.manager.sigar.impl.SpaceStatisticsServiceImpl"></bean>
//通过task标签,定义定时功能 <task:scheduled-tasks> <task:scheduled ref="spaceStatisticsService" method="statisticSpace" cron="59 59 23 * * ?" /> </task:scheduled-tasks>

要实现的代码部分为:

       

@Service
public class SpaceStatisticsServiceImpl implements SpaceStatisticsService
{
    @Override
    public void statisticSpace()
    {
        System.out.println("实现定时功能");
    }
}

 

 

总结:两种方法都能实现定时的功能,但明显第一种方式会比较简洁,而且更加方便。

posted @ 2017-11-03 14:49  香吧香  阅读(42914)  评论(7编辑  收藏  举报