构建定时任务

  1. 使用@EnableScheduling开启定时任务的支持
  2. 在方法上添加@Scheduled 注解声明定时器调用的频率 可以使用cron表达式
    cron表达式生成器: https://cron.qqe2.com/

每三秒输出一次时间

@Component
@EnableScheduling
public class ArticleTask {
    @Scheduled(cron = "0/3 * * * * ? ")
    public void article() {
        System.out.println(new Date());
    }
}

定时发布文章
业务逻辑:

  1. 每三秒从数据库中查询数据 判断预约时间 >= 当前时间修改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秒访问一次数据库 数据库压力比较大 可以使用消息队列来解决这个问题

posted @ 2021-09-22 14:10  RainbowMagic  阅读(44)  评论(0)    收藏  举报