MonoThreaded
MonoThreaded

Reputation: 12033

Java Timer next execution time

Meet Janitor, a timer that runs everyday at 3am.

Timer janitorTimer = new Timer();
TimerTask janitorWorker = new Janitor(); // Extending TimerTask
long delay = TimeUtils.getMillisUntilTomorrowAt( 3L * 3600000L); // Does what it says
janitorTimer.scheduleAtFixedRate( janitorWorker, delay, 24L * 3600000L);

At certain point in time I would like to know when is next janitorWorker execution.

Couldn't find anything relevant in Timer nor TimerTask. Feels that something either should already know.

Upvotes: 2

Views: 3751

Answers (3)

Spectorsky
Spectorsky

Reputation: 667

In the case when task hasn't executed yet, method scheduledExecutionTime is undefined. However, in my application, where once-executing task is scheduled, this method in fact returns scheduled time both before and after executing.
Note This behaviour is device-specific and non-documented. So, this approach should be verified for each device and cannot be recommended in general.

Upvotes: 0

Adel Boutros
Adel Boutros

Reputation: 10285

In TimerTask, exists a method called scheduledExecutionTime(). What it does is:

Returns the scheduled execution time of the most recent actual execution of this task.

Reference: http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html#scheduledExecutionTime%28%29

UPDATE:

Here is a new way.

Because it has a fixed rate, what you could do is call scheduledExecutionTime() add to it the fixedRate value and you then deduce the nextExecutionTime.

Upvotes: -1

cdc
cdc

Reputation: 2571

In your implementation of TimerTask you could expose the the nextExecutionTime, and then comapre that to the current time, see the mainLoop in Timer

Upvotes: 2

Related Questions