2009-01-22 96 views
4

Java中的ScheduledExecutorService對於以固定間隔或固定延遲重複任務非常方便。我想知道是否有類似現有的ScheduledExecutorService的東西,可以讓你指定一個時間來安排任務,而不是間隔,即「我希望這個任務在每天上午10點開始」。我知道你可以用Quartz來實現這個功能,但是如果可能的話我寧願不使用這個庫(這是一個很棒的庫,但是我寧願不要因爲某些原因而依賴它)。Java中的ScheduledExecutorService是否有類似cron的實現?

回答

2

您可以使用Timer類。具體來說,scheduleAtFixedRate(TimerTask任務,日期firstTime,長週期)。你可以在哪裏設置一項任務,在某一天的上午10點開始,每24小時重複一次。

+2

最大的問題與此特定的方法是,它沒有考慮夏令時變化考慮在內。 – GaryF 2009-01-23 10:05:08

+0

我選擇了這個答案,因爲它最準確地回答了我的問題,但我用我自己的答案解決了問題。 – GaryF 2009-01-23 16:19:37

+1

`ScheduledExecutorService`遠遠優於`Timer`類,原因很多。 – 2015-07-06 16:15:24

1

當您使用scheduleAtFixedRate時,您提供了延遲。所以延遲可能是上午10點和24小時的時間差。 即使使用計時器,這可能會有點偏差,所以您可以計劃一個任務,每次將適當的延遲添加到ScheduledExecutorService中。

2

多一點搜索在HA-JDBC已經變成了CronExecutorService。有趣的是,它對CronExpression類的Quartz依賴,但就是這樣。這並不算糟糕。

更新:我已經修復損壞的鏈接在新版本了點,但我不知道這是否是唯一的依賴更多的

1

ThreadPoolTask​​Scheduler,可以隨時使用外螺紋的管理是不是一個要求。在內部,它委託到 ScheduledExecutorService實例。 ThreadPoolTask​​Scheduler實際上實現了Spring的 TaskExecutor接口,因此可以儘可能快地使用單個實例進行異步執行,以及調度和潛在的循環執行。

凡爲CronTrigger()發生在cronExpression http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html

有關此解決方案的更多信息,請參閱春天文檔:https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; 
import org.springframework.scheduling.support.CronTrigger; 
import java.util.Date; 

public class CronTriggerSpringTest{ 
public static void main(String args[]){ 
    String cronExpression = "0/5 * * * * *"; 
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); 
    scheduler.initialize(); 
    scheduler.schedule(new Runnable() { 
     @Override 
     public void run() { 
      System.out.println("Hello Date:"+new Date()); 
     } 
    }, new CronTrigger(cronExpression)); 
} 
} 
相關問題