SpringBoot2.1.6简单使用Quartz实现定时任务

1、首先在porm.xml文件引入如下依赖:

2、新建一个任务类(如下面代码中的CommentLikeJob),这个类要继承QuartzJobBean父类,实现void executeInternal()方法,方法内为定时任务的业务逻辑(下面代码的业务逻辑可以不用理会),此外,可以在任务类里面通过@Autowired或者@Resource注入被Spring托管的Bean来使用。

import com.tkt.commons.utils.RedisUtil;
import com.tkt.dao.TktCommentLikeMapper;
import com.tkt.dao.TktCommentMapper;
import com.tkt.domain.TktCommentLike;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @description: 更新评论点赞数据任务
 * @author: xiexuan
 * @time: 2019/12/20 22:02
 */
public class ComentLikedJob extends QuartzJobBean {

    @Resource
    private TktCommentLikeMapper tktCommentLikeMapper;

    @Resource
    private TktCommentMapper tktCommentMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("定时任务开启======================");
        this.updateCommentLikeData();
        System.out.println("定时任务结束======================");
    }

    private void updateCommentLikeData(){
        Set<String> keys = RedisUtil.scan(stringRedisTemplate, "*like*");
        List<String> values = stringRedisTemplate.opsForValue().multiGet(keys);
        Iterator<String> keyIterator = keys.iterator();
        Iterator<String> valueIterator = values.iterator();
        while (keyIterator.hasNext()){
            String[] keyArray = keyIterator.next().split("::");
            Long commentId = Long.parseLong(keyArray[1]);
            Long userId = Long.parseLong(keyArray[2]);
            String[] valueArray = valueIterator.next().split("::");
            Date likedTime = new Date(Long.parseLong(valueArray[0]));
            int likedStatue = Integer.parseInt(valueArray[1]);
            Example example = new Example(TktCommentLike.class);
            example.createCriteria().andEqualTo("likedUserId", userId).andEqualTo("likedCommentId", commentId);
            TktCommentLike tktCommentLike = tktCommentLikeMapper.selectOneByExample(example);
            if (tktCommentLike != null){
                tktCommentLike.setLikedStatus(likedStatue);
                tktCommentLike.setUpdateTime(likedTime);
                tktCommentLikeMapper.updateByPrimaryKeySelective(tktCommentLike);
            }else {
                tktCommentLike = new TktCommentLike(userId, commentId, likedStatue, likedTime, likedTime);
                tktCommentLikeMapper.insert(tktCommentLike);
            }
        }

    }

3、新建一个配置类QuartzConfig,配置类里面返回一个JobDetail类和Trigger触发器类,Trigger类里面为定时任务的调度策略

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description: quartz配置类
 * @author: xiexuan
 * @time: 2019/12/23 21:35
 */
@Configuration
public class QuartzConfig {

    @Bean
    public JobDetail quartzDetail(){
        return JobBuilder.newJob(ComentLikedJob.class).withIdentity("commentLikeTaskQuartz").storeDurably().build();
    }

    @Bean
    public Trigger quartzTrigger(){
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInMinutes(5)
                .repeatForever();
        return TriggerBuilder.newTrigger().forJob(quartzDetail())
                .withIdentity("commentLikeTaskQuartz")
                .withSchedule(scheduleBuilder)
                .build();
    }
}

4、最后要在SpringBoot的Application启动类上面加上@EnableScheduling注解开启定时任务,就可以简单实现Quartz定时任务了。

发布了7 篇原创文章 · 获赞 0 · 访问量 2100

猜你喜欢

转载自blog.csdn.net/weixin_40759863/article/details/103683063