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"

 2.然后使用task配置扫描注解

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

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

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

第二种方法, 不使用注解, 直接配置

  首先

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

--  关于如何调整执行时间, 请在网上自行搜索

猜你喜欢

转载自www.cnblogs.com/Mr-Kenson/p/10021160.html