[英]Execute a method in java to check the time and execute a method on certain times
我正在運行一個IRC漫游器,它需要在兩個設定小時之間的聊天中回顯一條消息,並每隔幾分鍾執行一次此操作:
我試着做:
public void timerTest(int minH,int maxH, int minT){
boolean b = true;
boolean timeout = false;
while(b){
while(!timeout){
if(c.get(Calendar.HOUR_OF_DAY) >= minH && c.get(Calendar.HOUR_OF_DAY) <= maxH && c.get(Calendar.MINUTE) % minT == 0){
sendMessage(channel,spam1.getMessage());
timeout = true;
}
}
if(c.get(Calendar.MINUTE)%minT == 1){
timeout = false;
}
}
}
我通常希望在2到6之間每15分鍾發送一次垃圾郵件。我嘗試將其放入無休止的while循環中,但是不建議這樣做。 我尋找了Timer和TimerTask,但我不知道如何正確地做到這一點。 如果有人願意解釋我如何實現這一目標?
謝謝你^^
Java Timer
和TimerTask
並不真正適合您這樣的復雜調度需求。
我建議研究quartz
。 它允許您使用強大的cron
表達式進行計划。 我認為類似以下表達式的內容可能會有用:
*/15 2-6 * * * ?
一個非常簡單的想法可能是使用Spring和Task框架來執行此任務。請參閱http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html
您可以使用@Scheduled(cron = "*/15 2-6 * * * ?")
注釋您的Class方法。
或者,如果您不想包括spring依賴項,則可以創建ScheduledThreadPoolExecutor
的實例
// set the poolsize to 1
ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
scheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
// call method
}
}, 2,2, TimeUnit.HOURS);
這使您可以靈活地調度可以定期調用您的方法的可運行對象。 確保在應用程序關閉時關閉執行程序,否則您的應用程序可能會掛起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.