您的位置:首页 > 编程语言 > Java开发

spring定时任务@schedule

2015-11-26 16:19 375 查看
现在项目完成了,希望能够在项目中添加定时任务。比如取微信的accesstoken时,每7000s取一次。具体需要修改的地方如下:

1、在spring配置文件中添加task的声明

xmlns:task="http://www.springframework.org/schema/task"
 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd


2、配置 “异步和定时”的注解

<!-- 异步和定时 -->
<task:annotation-driven/>


3、新增一个类,用注解component,方法上用注解schedule即可。具体代码如下:

package com.ciji.zzaclient.schedule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.ciji.zzaservice.service.RegisterService;

@Component
public class ScheduleSpringTest {

@Autowired
RegisterService registerService ;

@Scheduled(cron ="0/3 * * * * ?")
public void updateWeixinAccessToken(){

System.out.println("我在定时执行。。。"+     registerService.selectByPk(44));
}

}


这样就实现了在项目中每隔三秒的定时执行的定时器代码。具体的定时规则可以根据具体的业务具体配置。

上面的定时只能每隔三秒执行一次,如果希望项目每次启动时候执行一次,然后每隔三秒执行一次。那么schedule的配置时间表达式如下:

@Scheduled(fixedRate = 1000*3)
public void updateWeixinAccessToken(){
System.out.println("我在定时执行。。。");
Thread.sleep(5000);
System.out.println(System.currentTimeMillis());
}


而且fixedRate 还有一个作用就是当前线程执行完成后才开始下一个任务开始。具体详见日志:

我在定时执行。。。
1452155492058
我在定时执行。。。
1452155497058
我在定时执行。。。


日志说明了线程是每隔五秒后才执行了下一次的定时,而不是每隔三秒就执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring schedule