spring schedule的简单实现

来源:互联网 发布:想做淘宝客服怎么申请 编辑:程序博客网 时间:2024/04/29 06:01

Schedule

关于spring一个计时器功能的实现
spring 的计时器是非常好用的,非常方便,无需配置多少东西即可运行。
ps,关于spring的基本配置就略过了...

1.搭建spring框架(其实就是导入一些jar包)
2.在src下的resources文件夹中新建一个配置文件,命名为spring-task.xml
3.在java文件夹下编写定时任务
4.编写测试文件,运行...

接下来就是详细步骤,主要记录2跟3.

spring-task.xml
<!-- xml 的头部 --><!-- 注意 .xsd 文件尽量不要带版本号 --><?xml version="1.0" encoding="UTF-8"?>    <beans xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xmlns:tx="http://www.springframework.org/schema/tx"        xmlns:aop="http://www.springframework.org/schema/aop"        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.xsd           http://www.springframework.org/schema/tx           http://www.springframework.org/schema/tx/spring-tx.xsd         http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop.xsd         http://www.springframework.org/schema/context          http://www.springframework.org/schema/context/spring-context.xsd          http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd      http://www.springframework.org/schema/task        http://www.springframework.org/schema/task/spring-task.xsd">      <task:annotation-driven /> <!-- 定时器开关-->       <!-- 这个bean对应的class是你编写了定时任务的java文件 -->    <bean id="schedule" class="com.spring.task.mytask"></bean>    </beans>

为什么不要在Spring的配置里,配置上XSD的版本号?因为如果没有配置版本号,取的就是当前jar里的XSD文件,减少了各种风险。而且这样约定大于配置的方式很优雅。

mytask.java
package com.spring.task;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class mytask {    @Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次        public void myTest(){              System.out.println("进入测试");        }     }

定时任务的java文件有两个地方需要注意
1.在类的前面添加@Component注解
2.在方法前面添加@Scheduled(cron="0/5 ? ")

TestTask类测试定时器
package com.spring.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestTask {    public static void main(String[] args) {        ApplicationContext context = new ClassPathXmlApplicationContext(                "classpath:spring-task.xml");    }}

在spring中只要读取到schedule的配置文件,spring就会开始启动定时器

0 0
原创粉丝点击