在java中执行一个方法来检查时间并在特定时间执行一个方法

时间:2011-03-12 16:14:22

标签: java

我正在运行一个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但我无法弄清楚如何正确地做到这一点。如果有人会如此善意地解释我是如何实现这一目标的?

谢谢^^

2 个答案:

答案 0 :(得分:1)

Java TimerTimerTask并不适合您的复杂调度需求。

我建议调查quartz。它允许您安排,例如,使用非常强大的cron表达式。我认为类似下面的表达式可能很有用:

*/15 2-6 * * * ?

答案 1 :(得分:0)

一个非常简单的想法可能是使用Spring和Task框架来完成这项任务 看一下 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

你可以简单地用你的Class方法注释 @Scheduled(cron = "*/15 2-6 * * * ?")

或者,如果您不想包含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);

这使您可以灵活地安排可以定期调用方法的runnable。确保在应用程序关闭时关闭执行程序,否则您的应用程序可能会挂起。