spring定时任务的实现

一、导入相关的包

<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);
    }
}


tip:延迟加载的话,需要启动之后访问一下


五、cron的语法参考

http://cron.qqe2.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值