springboot 使用 quartz
导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
配置quartz
@Configuration public class QuartzConfig { private static final String LIKE_TASK_IDENTITY = "LikeTaskQuartz"; @Bean public JobDetail quartzDetail() { return JobBuilder.newJob(QuestionViewCountTask.class).withIdentity(LIKE_TASK_IDENTITY).storeDurably().build(); } @Bean public Trigger quartzTrigger() { SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() // .withIntervalInSeconds(10) //设置时间周期单位秒 .withIntervalInHours(2) //两个小时执行一次 .repeatForever(); return TriggerBuilder.newTrigger().forJob(quartzDetail()) .withIdentity(LIKE_TASK_IDENTITY) .withSchedule(scheduleBuilder) .build(); } }
实现定时任务
public class QuestionViewCountTask extends QuartzJobBean { private static final Logger log = LoggerFactory.getLogger(QuestionViewCountTask.class); private QuestionService questionService; private RedisTemplate redisTemplate; private final SimpleDateFormat taskTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override protected void executeInternal(@NotNull JobExecutionContext jobExecutionContext) { ApplicationContext applicationContext = SpringContextUtil.getApplicationContext(); redisTemplate = applicationContext.getBean("redisTemplate", RedisTemplate.class); questionService = applicationContext.getBean("questionService", QuestionService.class); log.info("LikeTask-------- {}", taskTime.format(new Date())); Map<String, Integer> redisMap = redisTemplate.opsForHash().entries(RedisCacheConstant.QUESTION_KEY); if (redisMap.size() > 0) { Set<String> keys = redisMap.keySet(); List<QuestionPO> questionDOList = keys.stream().map(key -> { QuestionPO questionDO = new QuestionPO(); questionDO.setId(Long.valueOf(key)); questionDO.setViewCount(redisMap.get(key)); return questionDO; }).collect(Collectors.toList()); questionService.updateBatchById(questionDOList); } } }
获取spring
@Component public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } }