Lucas Kauffman
Lucas Kauffman

Reputation: 6891

Execute a method in java to check the time and execute a method on certain times

I'm running an IRC bot and it needs to echo a message in the chat between two set hours and do this every few minutes :

I tried to do :

        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;
                }
            }
        }

I normally want to spam a message every 15 minutes between 2 and 6. I tried putting it in an unendless while loop, but this is not recommended. I looked for Timer and TimerTask but I can't figure out how to properly do it. If someone would be so kind to explain how I can achieve this ?

thank you ^^

Upvotes: 0

Views: 538

Answers (2)

Joey
Joey

Reputation: 1349

a very simple idea might be to use Spring and the Task framework for doing this task Have a look at http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

You could simply annotate your Class method with @Scheduled(cron = "*/15 2-6 * * * ?")

Or if you don't want to include the spring dependencies, you could create an instance of 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);

This gives you the flexibility of scheduling a runnable which could just call your method periodically. Make sure you shutdown the executor on application shutdown, otherwise your app might hang.

Upvotes: 0

Johan Sj&#246;berg
Johan Sj&#246;berg

Reputation: 49187

Java Timer and TimerTask are not really fitted for complex scheduling needs such as yours.

I would recommend looking into quartz. It allows you to schedule e.g., using cron expressions which is quite powerful. I think something like the following expression could be useful:

*/15 2-6 * * * ?

Upvotes: 1

Related Questions