Spring Bootアプリケーションを書くときは、次のようなシナリオに遭遇します。テキストメッセージ、電子メール、その他の操作を定期的に送信する必要があります。また、フラグ、パラメーターなどを確認および監視することもできます。
時限タスクを作成します
Spring Bootでタイミングのあるタスクを書くのは非常に簡単です。次の例を使用して、5秒ごとに現在の時間を出力するために、Spring Bootでタイミングのあるタスクを作成する方法を紹介します。
スプリングブーツのメインクラスに@EnableSchedulingアノテーションを追加して、タイミングタスクの構成を有効にします
org.springframework.boot.springapplicationimport org.springframework.boot.autoconfigure.springbootapplicationimport org.springframework.scheduling.annotation.enabstcheduling/*** http://quanke.name on 2018/1/12。
時限タスク実装クラスを作成します
org.apache.commons.logging.logfactoryimport org.springframework.scheduling.annotation.scheduledimport org.springframework.stereotywe.componentimport java.text.simpledateformatimport java.util。 2018/1/12./@componentClass ScheduleDtasks {val log = logfactory.getLog(scheduledtasks :: class.java)!! private val dateformat = simpledateformat( "hh:mm:ss")@スケジュール(fixedrate = 1000)fun current -current -current -current -current -currentime $ {dateformat.format(date())} ")}}プログラムを実行すると、コンソールに次の出力が表示されます。タイミングタスクは正常に動作し始めます。
2018-01-21 23:09:09:01.112 Info 23832 - [Main] NQKotlin.Chaper11_8_1.ApplicationKT:8.024秒でApplicationKTを開始しました(8.724でJVMランニング)
2018-01-21 23:09:02.112 INFO 23832 - [Pool-2-Thread-1] nqkchaper11_8_1.task.scheduledtasks:現在の時刻、23:09:02
2018-01-21 23:09:03.042情報23832 - [Pool-2-Thread-1] nqkchaper11_8_1.task.scheduledtasks:現在の時刻、23:09:03
2018-01-21 23:09:04.042 INFO 23832 - [Pool-2-Thread-1] nqkchaper11_8_1.task.scheduledtasks:現在の時刻、23:09:04
2018-01-21 23:09:05.042情報23832 - [Pool-2-Thread-1] nqkchaper11_8_1.task.scheduledtasks:現在の時刻、23:09:05
@scheduleddetails
上記の紹介例では、@scheduled(fixtrate = 1000)注釈を使用して、1秒ごとに実行されるタスクを定義します。 @scheduledの使用は、次の方法で要約できます。
@Scheduled Annotationはシングルスレッドです。複数のスレッドが必要な場合は、@asyncを追加してください
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。