芯が強い人になるESTJ-A

# 异步任务,同步任务,邮件发送,定时任务,半夜12点日志输出

IT開発 Tags: 无标签 阅读: 269

异步任务

1主方法上开启

//需要在启动类上开启,异步任务
@EnableAsync
@SpringBootApplication
public class Springboot09MissionApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot09MissionApplication.class, args);
    }

}

2在方法上,加上注解

service

@Service
public class AsyncService {
    //你需要告诉spring,这个是一个异步的方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("数据正在处理ing");
    }
}

controller层负责,页面访问返回

@RestController
public class AsyncController {

    @Autowired//第一步把service层绑定过来!s
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();
        return"ok";
    }


}

邮件处理发送

        <!--mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

定时任务,半夜12点日志输出

TaskExecutor任务执行者
TaskScheduler任务调度者
@EnableScheduling
@Scheduled什么时候执行

Cron表达式


@Service
public class ScheduleService {


    //在特定的时间,执行这个方法
    //cron表达式
    //秒 分 时 日 月 周几
    @Scheduled(cron = "0 * * * * 0-7")
    public void hello(){
        System.out.println("hello,你被执行了");
    }
    

}