我读过很多关于使用计时器的答案。我试图了解如何将日期(或者我不能?)传递给方法 scheduleAtFixedRate它有两种形式:
1) void sheduleAtFixedRate(TimerTask任务,长延迟,长周期)
2) void ScheduleAtFixedRate(TimerTask task, Date firstTime, long period)
(我现在指的是这种形式)
我正在使用第二种形式,例如:
//creating a new instance of timer class
Timer timer = new Timer();
TimerTask task = new Helper();
Date date = new Date();
timer.scheduleAtFixedRate(task, date, 5000);
在没有任何指定值的情况下使用date
。但在这个例子中我可以指定日期吗?如果我错了,请纠正我。
最佳答案
看来您对 javadoc 感到困惑。
只有一个理由使用日期
相关代码:
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).
换句话说:当您打算设置一个 Date 对象来表示 2018 年 8 月 1 日,并且希望您的代码在那一天运行时,那么您可以使用上面的代码来做到这一点。
换句话说:您使用日期算术来计算任务在特定日期/时间开始所需的延迟。
需要明确的是:问题中您自己的代码示例(timer.scheduleAtFixedRate(task, date, 5000);
),此代码无效!
该类中没有方法直接采用Date对象。所有方法仅接受长值,表示初始延迟!
关于java - 我可以使用 Timer 类将日期传递给 ScheduleAtFixedRate 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51443660/