定时执行任务-springboot

定时执行任务-springboot

先看两个接口

这两个接口springboot已经帮我们封装好了,我们不需要去手动使用

TaskScheduler //任务调度者
TaskExecutor //任务执行者

具体步骤:

  1. 在启动类上添加这个注解:
@EnableScheduling//开启定时功能的注解
  1. 给需要定时任务的方法添加@Scheduled(cron="0 * * * * *")注解
@Service
public class ScheduledService {
    //cron
    //秒 分 时 日 月 周几(0-7) 年
    //每到0秒执行一次
    @Scheduled(cron="0 * * * * *")
    /*
    30 15 10 * * ? 每天10点15分30秒执行一次
    30 0/5 10,18 * * ?  每天10点和18点,每隔5分钟的30秒执行一次
     */
    public void hello(){
        System.out.println("hello,你被执行了!");
    }
}
  1. 执行springboot就可以了,因为它是异步任务,只要到时间就会跑,不需要写Controller请求响应。

这也很简单,就是加了两个注解。

posted on 2022-04-08 10:29  汪汪程序员  阅读(432)  评论(0编辑  收藏  举报

导航