invzbl3
invzbl3

Reputation: 6470

Can I pass date to the method scheduleAtFixedRate using class Timer?

I've read a lot of answers about using Timer. I'm trying to understand how to pass date (or I can't?) to the method scheduleAtFixedRate which has two forms:

1) void sheduleAtFixedRate(TimerTask task, long delay, long period)

2) void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) (I mean this form now)

And I'm using 2nd form like:

//creating a new instance of timer class
        Timer timer = new Timer();
        TimerTask task = new Helper();

        Date date = new Date();

        timer.scheduleAtFixedRate(task, date, 5000);

Where date used without any specified values. But can I specify date, in this example? Correct me, if I'm wrong, please.

Upvotes: 1

Views: 522

Answers (1)

GhostCat
GhostCat

Reputation: 140523

It seems that you got confused by the javadoc.

There is only one reason to use Date related code:

All schedule methods accept relative delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a Date to the required form. For example, to schedule at a certain future date, you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS).

In other words: when you intend to setup a Date object to represent the 1st of August 2018, and you want your code to run at that day, then you could do so using the above code.

In other words: you use Date arithmetic to compute the delay required to have the task start at a specific date/time.

Just to be really clear: your own code example from the question ( timer.scheduleAtFixedRate(task, date, 5000);), this code is invalid!

There is no method in that class that takes a Date object directly. All methods only accept long values, representing an initial delay!

Upvotes: 1

Related Questions