spring @Scheduled 实现定时任务的注意事项

本文介绍使用Spring框架实现定时任务清理缓存的方法,包括通过注解@EnableScheduling启用定时任务及使用@Scheduled注解定义具体任务。同时,还介绍了另一种方式即通过Spring配置文件来配置定时任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:使用 @EnableScheduling 注解

先上代码

package com.eason.spring.cache;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.eason.spring.dao.entity.User;
import com.eason.spring.dao.mapper.UserMapper;
@EnableScheduling
@Service(value = "userService")
public class UserService {

    private static final Log LOGGER = LogFactory.getLog(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Cacheable(value = "userCache")
    public User getUser(String uid) {
        LOGGER.info("Load user from DB, uid=" + uid);
        return userMapper.getUser(uid);
    }

    /**
     * 将当前更新的user从cache里删除
     * 
     * @param user
     */
    @CacheEvict(value = "userCache", key = "#user.getUid()")
    public void updateUser(User user) {
        userMapper.update(user);
    }

    /**
     * 定时任务, 每分钟清除一次缓存
     */
    @Scheduled(cron = "0/1 * * * * ?")
    @CacheEvict(value = "userCache", allEntries = true)
    public void reload() {
        LOGGER.info("Remove all entries from userCache.");
    }
}

 

注意事项:

1、spring的@Scheduled注解  需要写在实现上、

2、 定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true、具体就去百度google吧)

3、实现类上要有组件的注解@Component

 

方法二:使用spring配置文件,这时就不需要给实现类加上@EnableScheduling 和 @Component 注解,这样我们就可以将bean定义在spring的配置文件里了。

    <context:component-scan base-package="com.eason.spring.cache" />

    <context:annotation-config />

    <task:annotation-driven />

注意事项:需要 spring 4.x

转载于:https://www.cnblogs.com/longzhaoyu/p/4992160.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值