一异步任务 Async
@Service
public class AsyncService {
    @Async
        public  void hello(){
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("处理数据中...");
        }
}
@RestController
public class AyncController {
    @Autowired
    AsyncService asyncService;
    @GetMapping("/hello")
    public  String hello(){
     asyncService.hello();
     return "success";
    }
}
加上一个Async注解 springboot启动项加上EnableAsync即可开启异步任务
@EnableAsync  //开启异步任务
@EnableScheduling  //开启定时任务
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
即可实现异步任务
二定时任务
@Service
public class Schedule {
   // @Scheduled(cron = "0 * * * * MON-FRI")  //整秒的时候打印
  // @Scheduled(cron = "0-4 * * * * MON-FRI")   //0-4秒的时候会打印
   @Scheduled(cron = "0/4 * * * * MON-FRI")  // 0秒启动 每4秒打印一次
   public  void hello (){
         System.out.println("兽人永不为奴!");
     }
}
在启动类加上@EnableScheduling  //开启定时任务
启动项目即可开启springboot定时任务
定时任务打印语句截图

图片.png
cron表达式范例
每隔1分钟执行一次:0 */1 * * * ?
每天23点执行一次:0 0 23 * * ?
每天凌晨1点执行一次:0 0 1 * * ?
每月1号凌晨1点执行一次:0 0 1 1 * ?
每月最后一天23点执行一次:0 0 23 L * ?
每周星期天凌晨1点实行一次:0 0 1 ? * L
在26分、29分、33分执行一次:0 26,29,33 * * * ?
每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?
项目码云仓库:https://gitee.com/zdwbmw/springboot_Task
springboot异步任务,定时任务.