@spring的定时任务
最近在项目中遇到了一个问题,需要用到一个定时任务来定时更新redis中的数据,那么就使用到了spring中的定时任务,下面来记录一下是如何使用的
1、在applicationContext.xml配置文件中添加如下的配置
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
2、配置注解驱动
<task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
<task:scheduler id="qbScheduler" />
3、写定时任务类
@Component
public class ScheduledTask {
@Autowired
RedisTemplate redisTemplate;
@Scheduled(fixedRate = 5 * 3600 * 1000) // 每5小时执行一次
public void refreshRedisData() {
//TODO根据自己的业务逻辑,写定时任务需要干哪些事
//例如:往redis中存数据
redisTemplate.opsForValue().set("endTime", (new Date()).toString(), Contants.TIME, TimeUnit.HOURS);
}
}
注释:也可以使用cron表达式指定具体几点开始执行
@Scheduled(cron = “0 0 2,8,14,20 * * ?”) // 每天2点、8点、14点、20点执行一次