簡體   English   中英

如何在Spring config.xml中配置Cron時區?

[英]How to configure Cron timezone in a Spring config.xml?

我有一個帶有Cron任務的Spring配置xml文件。 該任務會在我的計算機上定期執行。 如何在xml文件中配置此任務以使用莫斯科時區(與我的時區不同)?

<task:scheduler id="scheduler" pool-size="1"/>

<task:scheduled-tasks scheduler="scheduler">
    <task:scheduled ref="productTask" method="loadProduct" cron="0 0 10 * * *"/>
</task:scheduled-tasks>

編輯:我仔細檢查了語法,並更改了一點代碼。 但這對我仍然不起作用。 下面提供了我想到的最后一個配置。 在這里,我得到以下異常: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Cron expression must consist of 6 fields (found 1 in "moscowTimeCronSchedule") Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Cron expression must consist of 6 fields (found 1 in "moscowTimeCronSchedule")

因此,任務“調度程序”需要cron表達式而不是cron="moscowTimeCronSchedule" 我需要弄清楚如何將bean引用傳遞給它而不是純cron表達式。

<task:scheduler id="scheduler" pool-size="1"/>

    <bean id="moscowTimeZone" class="java.util.TimeZone" factory-method="getTimeZone">
        <constructor-arg type="java.lang.String" value="Europe/Moscow"/>
    </bean>

    <bean id="moscowTimeCronSchedule" class="org.springframework.scheduling.support.CronTrigger"
          c:expression="*/15 * * * * *"
          c:timeZone-ref="moscowTimeZone"/>

    <task:scheduled-tasks scheduler="scheduler">
        <task:scheduled ref="productTask" method="loadProduct" cron="moscowTimeCronSchedule"/>
    </task:scheduled-tasks>

我發現此鏈接很有用,但沒有回答問題:如何傳遞bean而不是cron表達式。 http://websystique.com/spring/spring-job-scheduling-using-xml-configuration/

當Spring配置CronTask時,它使用一個簡單的構造函數形式,該形式接受String 您需要使用第二個構造函數,該構造函數接受CronTrigger 這應該工作(盡管,坦率地說,我還沒有測試過):

<bean
  id="moscowTimeZone"
  class="java.util.TimeZone"
  factory-method="getTimeZone">
    <constructor-arg type="java.lang.String" value="Europe/Moscow"/>
</bean>

<bean
  id="moscowTimeCronSchedule"
  class="org.springframework.scheduling.support.CronTrigger">
    <constructor-arg type="java.lang.String" value="0 0 10 * * *"/>
    <constructor-arg type="java.util.TimeZone" ref="moscowTimeZone"/>
</bean>

<task:scheduled-tasks scheduler="scheduler">
    <task:scheduled ref="productTask" method="loadProduct" trigger="moscowTimeCronSchedule"/>
</task:scheduled-tasks>

我在這里所做的:

  1. 構造了對莫斯科時區的引用,並將其保存為Spring配置中的bean。

  2. 使用該時區和cron表達式將Cron Trigger實例構造為另一個bean

  3. 在計划任務構造函數中使用了Cron觸發器。

誠然,這個解決方案有點冗長,但是聽起來應該做得到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM