• 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");
        }
        
    }
  • 相关阅读:
    Unix系统中system函数的返回值
    vim 插件 for gbasic
    arch初认识
    TI IPNC Web网页之进阶修改
    Ti IPNC Web网页之ActiveX控件
    TI IPNC Web网页之网页修改教程
    OI,再见
    [OI]省选前模板整理
    OI刷题录——hahalidaxin
    51nod 小Z的trie(Trie+广义SAM)
  • 原文地址:https://www.cnblogs.com/banma/p/6549098.html
Copyright © 2020-2023  润新知