spring定时任务的配置与实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40606932/article/details/83926629

 

在spring 中 基于注解的 定时配置很简单,只需要三步哦,如下: 1、在类名前加@Component注解,标记该bean,也就是配置扫描标记。 2、在该类下的方法前加定是配置注解,@Schedule("cron= 0/30 * * * * *")。 3、添加配置文件(如下)。

一、导入相关的包

<properties>

<springVersion>4.1.6.RELEASE</springVersion>

</properties>

二、在web.xml中配置spring

<listener>

<description>Spring监听器</description>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

三、在applicationContext.xml中配置监听器

1、 配置头文件中必须要有

xmlns:task="http://www.springframework.org/schema/task"

2、xsi:schemaLocation=里面必须要有

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task.xsd

3、task的类必须要在spring扫描的的包下面

<context:annotation-config />

<context:component-scan base-package="com.test.task" />

<task:annotation-driven/>

4、启动定时任务

<task:annotation-driven/>

四、写定时任务类

package com.test.task;

import java.text.DateFormat;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

@Component

public class TestTask {

@Scheduled(cron = "*/5 * * * * ?")

public void print5(){

String time = DateFormat.getDateTimeInstance().format(new Date());

System.out.println("我5秒打印一次"+time);

}

@Scheduled(cron = "*/4 * * * * ?")

public void print4(){

String time = DateFormat.getDateTimeInstance().format(new Date());

System.out.println("我4秒打印一次"+time);

}

}

 

Spring 定时任务执行两次:web.xml加载了两次spring.xml配置文件

 

猜你喜欢

转载自blog.csdn.net/qq_40606932/article/details/83926629