P2 Sping Boot定时器实战 读取问题列表
程序员文章站
2022-06-09 10:57:51
...
有两方式实现:
1.获取所有问题,循环获取标签,然后将标签与问题数存储在一个集合里
2.获取所有标签,查询每个标签有多少个问题被它引用(时间复杂度大)
设置定时执行官网:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html
"0 0 * * * *" = the top of every hour of every day.
"*/10 * * * * *" = every ten seconds.
"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
"0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day.
"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
"0 0 0 25 12 ?" = every Christmas Day at midnight
使用第一种,使用定时任务将问题从数据库中取出来
package life.majiang.community.schedule;
import com.github.pagehelper.PageHelper;
import life.majiang.community.dto.QuestionDTO;
import life.majiang.community.mapper.QuestionMapper;
import life.majiang.community.model.Question;
import life.majiang.community.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 热门标签定时器,此处是测试定时任务(每隔5秒打印日志)
* 注意:需在main方法的那个类上添加@EnableScheduling注解
*/
@Component
@Slf4j
public class HotTagTasks {
private List<QuestionDTO> list = null;
@Autowired
private QuestionService questionService;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 1000)
//@Scheduled(cron = "0 0 1 * * *")//每天凌晨1点执行
public void hotTagSchedule() {
int offset = 0;
int limit = 5;
String search=null;
log.info("hotTagSchedule start {}", dateFormat.format(new Date()));
while (offset ==0 || list.size()==limit){
list = questionService.list(search, offset, limit);
for (QuestionDTO questionDTO : list) {
log.info("list question :{}",questionDTO.getId());
}
offset +=limit;
}
log.info("hotTagSchedule stop {}", dateFormat.format(new Date()));
}
}
测试结果:
上一篇: 字符串截取函数