spring boot task

任务

定时任务

  • 开启 @EnableScheduling 注解
@SpringBootApplication
@EnableScheduling
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
}
  • 定义任务类 启用 @Component @Scheduled 注解 (cron 写法参考linux crontab)
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class CronTask {
    
    //每过5秒执行一次 
    @Scheduled(cron = "0/5 * * * * *")
    public void hello(){
        System.out.println("hello!");
    }
}

异步任务

  • 增加 @EnableAsync 注解开启异步支持
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class ExampleApplication {

	public static void main(String[] args) {
		SpringApplication.run(ExampleApplication.class, args);
	}
}
  • 编写异步任务 增加 @Component @Async 注解
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AsyncTask {
    @Async
    public void async1(){
        try{
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }
    @Async
    public void async2(){
        try{
            Thread.sleep(700);
        }catch (Exception e){

        }
    }

    @Async
    public void async3(){
        try{
            Thread.sleep(500);
        }catch (Exception e){

        }
    }

}