spring的定时任务

@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点执行一次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值