【发布时间】:2015-06-15 07:19:41
【问题描述】:
我必须安排一个方法在启动时执行,然后每隔 1 分钟定期执行一次。
为此我已经这样做了:
public void init(){
loadConfig(); //method which needs to be executed periodically
Timer scheduler = new Timer();
scheduler.scheduleAtFixedRate(loadConfig(),60000,60000);
}
这是一个错误,因为scheduleAtFixedRate 的第一个参数是Runnable 类型。
我需要建议的是,如何使我的loadConfig 方法Runnable 并在我在调度程序启动之前执行loadConfig() 时仍然执行它。
目前代码结构如下:
public class name {
public void init() {
...
}
...
public void loadConfig() {
...
}
}
编辑:这是我已经尝试过的
public void init(){
loadConfig();
Timer scheduler = new Timer();
scheduler.scheduleAtFixedRate(task,60000,60000);
}
final Runnable task = new Runnable() {
public void run() {
try {
loadConfig();
} catch (Exception e) {
e.printStackTrace();
}
}
};
【问题讨论】:
-
您使用的是什么调度程序?你用谷歌搜索过
Runnable是什么吗? -
我这样做了,因此编写了我在编辑中添加的代码。但是即使文档清楚地说明了参数,它仍然会出错: scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
-
如果文档指定了 4 个参数,而你只给了 3 个,那么显然不会编译
-
然而 eclipse 提供了以下提示:Timer 类型中的方法 scheduleAtFixedRate(TimerTask, long, long) 不适用于参数(Runnable, int, int, TimeUnit)。因此,我假设最后一个参数是可选的。
-
我猜你使用了错误的文档。你用的是什么定时器?您使用的是什么类型的文档?
标签: java methods timer scheduler runnable