動作確認環境
- Java 8
- TERASOLUNA Server Framework for Java (5.4.1.RELEASE)
- Spring Framwork 4.3.14.RELEASE
- Spring Integration 4.3.14.RELEASE
XMLでPollerを定義する
Spring Integrationには、Poller
という定期的に実行する仕組みがありますが、XML(<int:poller>
)で定義する場合に、fixed-delay
やfixed-rate
といった実行間隔を設定できる属性は用意されているのですが、初期値遅延の属性は用意されていません。
以下は4.3.xのxsdファイルのPoller
に関する記述です。
spring-integration-4.3.xsd
<xsd:element name="poller">
<xsd:annotation>
<xsd:documentation>
Defines a top-level poller - 'org.springframework.integration.scheduling.PollerMetadata'.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="basePollerType">
<xsd:attribute name="id" type="xsd:string" />
<xsd:attribute name="default" type="xsd:boolean" default="false" />
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="basePollerType">
<xsd:annotation>
<xsd:documentation>
Defines the configuration metadata for a poller.
</xsd:documentation>
</xsd:annotation>
<xsd:sequence>
<!-- 略 -->
</xsd:sequence>
<xsd:attribute name="fixed-delay" type="xsd:string">
<xsd:annotation>
<xsd:documentation>Fixed delay trigger (in milliseconds).</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="ref" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:documentation>
Allows this poller to reference another instance of a top-level poller.
[IMPORTANT] - This attribute is only allowed on inner poller definitions.
Defining this attribute on a top-level poller definition will result in a configuration exception.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="fixed-rate" type="xsd:string">
<xsd:annotation>
<xsd:documentation>Fixed rate trigger (in milliseconds).</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<!-- 略 -->
</xsd:complexType>
そのため、例えばアプリケーション起動後1分経過後、接続に問題ないか定期的に監視メッセージを投げたいという仕様を満たせません。
PeriodicTrigger
で解決
で、調べた結果、なんと2011年にフォーラムで同じような質問をしていた方がいました。
その回答によると、PeriodicTrigger
という定期的に実行するトリガクラスに初期遅延を設定し、Poller
のtrigger
属性に設定すればよいようです。
というわけで、以下のようにPeriodicTrigger
をビーン定義してPoller
のtrigger
属性に設定したところ、アプリケーション起動後60秒経過してから60秒間隔で監視メッセージが投げられることを確認できました。
<!-- 監視メッセージを投げるアダプタ -->
<int:inbound-channel-adapter id="monitoringAdapter"
auto-startup="true" expression="'monitor'.bytes"
channel="inboundMonitoringChannel">
<int:poller trigger="monitoringTrigger" />
</int:inbound-channel-adapter>
<!-- 監視メッセージを投げる間隔 -->
<!-- 初期遅延60秒後に60秒間隔で発火 -->
<bean id="monitoringTrigger" class="org.springframework.scheduling.support.PeriodicTrigger"
c:period="60" c:timeUnit="SECONDS" p:initialDelay="60" />
おわりに
- Poller
- Task Executor
- Trigger
の違いがあやふやになってきました。
今回のサンプルコードはGitHubで公開しています(内容は少し変えました)。