(转)spring计划任务,springMvc计划任务,Spring@Scheduled,spring定时任务

一、计划任务实现类

1、用@Component注解标识计划任务类,这样spring可以自动扫描

2、在方法中使用注解标识要执行的方法:@Scheduled(cron="*/30 * * * * *")

3、周期可以使用cron,或者fixedRate,fixedRate=1000*30表示30秒执行一次,cron请自行百度或看下面的代码的说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component 
public class SpringTask { 
   
    /**
     * cron表达式:* * * * * *(共6位,使用空格隔开,具体如下) 
     * cron表达式:*(秒0-59) *(分钟0-59) *(小时0-23) *(日期1-31) *(月份1-12或是JAN-DEC) *(星期1-7或是SUN-SAT) 
     * 注意: 30 * * * * * 表示每分钟的第30秒执行,而(*斜杠30)表示每30秒执行
     
     * */ 
    @Scheduled(cron="*/30 * * * * *") 
    public void firstTask(){ 
        System.out.println("==============it is first task!时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); 
    
}

二、需要在spring.xml配置文件中加入命名空间(xmlns:task)

本项目采用了spring4.1,所以用的是4.1

1
2
3
4
5
6
7
8
9
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:task="http://www.springframework.org/schema/task" 
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd 
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

三、增加包的扫描,一般在spring.xml文件都会有

主要是这个:<context:component-scan base-package="com.spring.*"></context:component-scan>

1
2
3
<context:component-scan base-package="com.spring.*"> 
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 
    </context:component-scan>

四、在spring.xml文件中配置计划任务

1
2
<task:annotation-driven scheduler="taskScheduler" mode="proxy"/>   
<task:scheduler id="taskScheduler" pool-size="10"/>
 

也可以简单点配置,如下:

1
<task:annotation-driven />

 五、然后启动web项目,就会看到每30秒就打印信息出来。

六、如果需要用到service类,可以注入。

1
2
@Autowired 
private PushRecordService pushRecordService;

转自:http://fanshuyao.iteye.com/blog/2267243

posted @   人艰不拆_zmc  阅读(305)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2014-08-06 Biorhythms(中国剩余定理)
2014-08-06 Sequence(priority_queue)
2014-08-06 Message Flood(map)
2014-08-06 POJ3096:Surprising Strings(map)
2014-08-06 Hardwood Species(stl map)
2014-08-06 C++(STL)&&树-堆结构练习——合并果子之哈夫曼树
点击右上角即可分享
微信分享提示