tags:

views:

452

answers:

3

I'm looking for some guidance on how to manage multiple timer tasks. I'd like to be able to dynamically create timers and then when each timer is finished, it'll reset itself.

Example:

Timer 1 - perform action x - reset to perform action x again in 30 minutes

Timer 2 - perform action y - reset to perfom action y again in 10 minutes

+1  A: 

The following code creates a timer and executes it every 1000 ms after an initial delay of 500 ms. You can easily define two or more timers this way.

TimerTask task = new TimerTask() {
    @Override
    public void run() {
        System.out.println( "exec" );
    }
};

new Timer().scheduleAtFixedRate( task, 500, 1000 );
tangens
Well I'd actually like to reschedule the task after previous task has completed (to ensure they aren't overlapping).
+4  A: 

What you want is the ScheduledExecutorService.

It allows you to schedule tasks to run at a given time or at a given rate.

Kevin
A: 

Perhaps it could be worth reviewing Quartz Enterprise Job Scheduler

Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components or EJBs.

antispam