Perform a task each interval

93 views Asked by At

So I'm trying to schedule a time instance where it repeats every 10 seconds. Right now I have something that does a task after 10 seconds, but how do I make it so that it resets after doing so.

this.schedule = TimerManager.getInstance().schedule(new Runnable() {
        @Override
        public void run() {
            chrs.get(0).getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(100100), chrs.get(0).getPosition());
        }

    }, time);

}

time is equal to 10000 milliseconds, and thus 10 seconds.

3

There are 3 answers

5
varren On BEST ANSWER

1) Create ScheduledExecutorService

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

2) Create and schedule your Runnable:

Runnable task = new Runnable() {
    @Override
    public void run() {
        System.out.println("Done:" + new Date(System.currentTimeMillis()));
        // some long task can be here
        executor.schedule(this, 10, TimeUnit.SECONDS);
    }
};
//can be 0 if you want to run it fist time without 10 sec delay
executor.schedule(task, 10, TimeUnit.SECONDS); 

If you don't care about runnable duration and always want to fire event every 10 secs

executor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        System.out.println("Done:" + new Date(System.currentTimeMillis()));
    }
}, /* same, can be 0*/ 10 , 10, TimeUnit.SECONDS);

3) Use this when you exit program

executor.shutdown();
0
user1675642 On
0
iouhammi On

You can use scheduleAtFixedRate method instead.

See this question Creating a repeating timer reminder in Java