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");
        }
        
    }
  • 相关阅读:
    net core 使用 rabbitmq
    asp.net core WebApi 返回 HttpResponseMessage
    asp.net core 2.1 WebApi 快速入门
    JQuery EasyUI combobox动态添加option
    php截取字符去掉最后一个字符
    JQuery EasyUI Combobox的onChange事件
    对于不返回任何键列信息的 selectcommand 不支持 updatecommand 的动态 sql 生成
    Access2007 操作或事件已被禁用模式阻止解决办法
    Easyui 中 Tabsr的常用方法
    Win 7 IE11不能下载文件,右键另存为也不行
  • 原文地址:https://www.cnblogs.com/banma/p/6549098.html
Copyright © 2011-2022 走看看