Spring Bootタイミングタスクを実現する4つの方法

2794 ワード

Timerという現在プロジェクトで使われているものは少なく、直接demoコードを貼ります.詳しくはapiをご覧いただけます
public class TestTimer {
public static void main(String[] args) {
   TimerTask timerTask = new TimerTask() {
       @Override
       public void run() {
           System.out.println("task  run:"+ new Date());
       }

   };

   Timer timer = new Timer();

   //                          。    3     
   timer.schedule(timerTask,10,3000);

}
}ScheduledExecutorServiceを使用するこの方法はTimerと同様で、demoを直接見ます.
public class TestScheduledExecutorService {
public static void main(String[] args) {
   ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

   //   :1、    2、         
   //      3、       4、      
   service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+new Date()), 0, 3, TimeUnit.SECONDS);

}
}Spring Taskの簡単なタイミングタスクSpringBootプロジェクトでは、注釈を優雅に使用してタイミングタスクを実現することができ、まずプロジェクトを作成し、依存性をインポートすることができます:org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter org.projectlombok lombok true org.springframework.boot spring-boot-starter-test testタスククラスを作成するには、次の手順に従います.
@Slf4j
@Component
public class ScheduledService {
@Scheduled(cron="0/5****)public void scheduled(){log.info("=====>>>>>>>>>cron{}",System.currentTimeMillis();}
@Scheduled(fixedRate=5000)public void scheduled 1(){log.info("=====>>>>>>fixedRate{}",System.currentTimeMillis();}
@Scheduled(fixedDelay = 5000) public void scheduled2() { log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis()); }
}メインクラスで@EnableScheduling注記を使用してタイミングタスクのサポートを開始し、プロジェクトを開始
推奨:Springは計画を迅速に開始します.3つのタイミングタスクが実行され、同じスレッドでシリアルに実行されていることがわかります.1つのタイミングタスクしかない場合は、間違いなく問題ありません.タイミングタスクが増えると、1つのタスクが詰まってしまうと、他のタスクも実行できません.Javaテクノロジースタックの微信公衆番号に注目し、バックグラウンドでキーワード:springに返信し、より多くのスタック長が整理したSpringシリーズのテクノロジー乾物を得ることができます.
マルチスレッドは、従来のSpringプロジェクトではxmlプロファイルにtaskの構成を追加できますが、SpringBootプロジェクトではconfig構成クラスを使用して構成を追加するのが一般的なので、AsyncConfigクラスを新規作成します.Javaテクノロジースタックの微信公衆番号に注目し、バックグラウンドでキーワード:springに返信し、より多くのスタック長が整理したSpringシリーズのテクノロジー乾物を得ることができます.
@Configuration @EnableAsync public class AsyncConfig {
/*
 *          @Value      
*/

private int corePoolSize = 10; private int maxPoolSize = 200; private int queueCapacity = 10;
@Bean public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.initialize(); return executor; }
}深センウェブサイト建設www.sz 886.com