zoukankan      html  css  js  c++  java
  • Spring定时器@Scheduled

    以前用java自带的Timer做过定时器,但是在web项目中启动tomcat以后不能马上启动定时器,还需要手动触发,很不方便。于是就想到了在配置文件里直接写入。正好Spring有自带的定时器@Scheduled,所以做了个例子。

    首先我是用的ssm框架,spring-mvc.xml文件整合了配置,当然别的框架也行,只要有Spring。

    spring配置文件如下:

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:task="http://www.springframework.org/schema/task"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                            http://www.springframework.org/schema/context  
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                            http://www.springframework.org/schema/mvc  
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                            http://www.springframework.org/schema/task  
                            http://www.springframework.org/schema/task/spring-task-3.1.xsd  ">
                            
        <bean id="singer" class="com.timer.mytimer.MyTimer"/>  
        <task:annotation-driven />  

    xmlns 多加下面的内容

    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.1.xsd  

    ask任务扫描注解

    <task:annotation-driven/>

    最后是添加bean

    <bean id="singer" class="com.timer.mytimer.MyTimer"/> 

    java代码

    package com.timer.mytimer;
    
    import org.springframework.scheduling.annotation.Scheduled;
    
    public class MyTimer {
        public static void main(String[] args) {
            System.out.println("xxxx");
        }
        
        //@Scheduled(cron="0/5 * *  * * ? ")   每5秒执行一次  
        @Scheduled(fixedDelay=6000)                // 每6秒执行一次  fixedDelay单位是毫秒
        public void timeTigger(){
            System.out.println("sssss");
        }
        
    }
  • 相关阅读:
    uva 1511 最小生成树
    百度之星2017初赛A-1006-度度熊的01世界
    工作5年总结-总结这两年在阳光的日子
    在visual studio中查看源代码
    根据C#编程经验思考编程核心
    项目的可维护可持续性思考
    java学习
    What is ASP.NET SignalR
    WCF 和 ASP.NET Web API
    wcf服务
  • 原文地址:https://www.cnblogs.com/banma/p/6549098.html
Copyright © 2011-2022 走看看