构建定时任务
- 使用
@EnableScheduling
开启定时任务的支持 - 在方法上添加
@Scheduled
注解声明定时器调用的频率 可以使用cron表达式
cron表达式生成器:https://cron.qqe2.com/
每三秒输出一次时间
@Component
@EnableScheduling
public class ArticleTask {
@Scheduled(cron = "0/3 * * * * ? ")
public void article() {
System.out.println(new Date());
}
}
定时发布文章
业务逻辑:
- 每三秒从数据库中查询数据 判断预约时间 >= 当前时间修改is_appoint状态为立即发布 也就是0
sql调用now()
函数获取当前时间
若预约状态为预约发布 且当前时间<= 预约时间 修改状态为立即发布
@Mapper
public interface ArticleCustomMapper {
@Update("update article set is_appoint = 0 where is_appoint = 1 and publish_time <= now()")
public void updateArticleAppoint();
}
service直接调用mapper
@Override
public void updateArticleAppoint() {
articleCustomMapper.updateArticleAppoint();
}
使用spring定时任务每3秒修改一次
@Component
@EnableScheduling
public class ArticleTask {
@Autowired
private ArticleService articleService;
@Scheduled(cron = "0/3 * * * * ? ")
public void article() {
articleService.updateArticleAppoint();
System.out.println(new Date());
}
}
这样每3秒访问一次数据库 数据库压力比较大 可以使用消息队列来解决这个问题
虽然道路是曲折的,但前途是光明的。