• 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("实现定时功能");
        }
    }

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

  • 相关阅读:
    调试 camera 时记录点滴
    奇偶场的合并&yuv2rgb
    拓宽视野
    Eclipse中看不到jsp的页面效果
    极品函数
    Visual C# 2005中让ComboBox控件显示出多个数据源属
    C#——如何使tableLayoutPanel 不闪烁
    ASP.NET中JSON的序列化和反序列化
    有钱慷慨的管理者,有钱吝啬的管理者,无钱思想慷慨的管理者,无钱思想吝啬的管理者都有各自的下场白
    C# WinForm开发系列 ComboBox
  • 原文地址:https://www.cnblogs.com/zjdxr-up/p/7778135.html
Copyright © 2020-2023  润新知