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");
        }
        
    }
  • 相关阅读:
    LeetCode 234——回文链表
    【转】Jmeter常见问题
    【转】JMeter 聚合报告之90% Line参数说明
    【转】Jmeter + DadBoby 安装使用
    【转】JMeter远程测试
    【转】关于一个Jmeter interface testing的实例
    【转】Jmeter 代理服务器录制脚本
    【转】Jmeter和LR上传文件和下载
    【转】Jmeter JDBC请求的问题
    【转】Jmeter的正则表达式未正确提取数据
  • 原文地址:https://www.cnblogs.com/banma/p/6549098.html
Copyright © 2011-2022 走看看