【发布时间】:2019-04-29 23:17:16
【问题描述】:
我有一个程序,我可以在其中插入文件路径及其对应的参数到表。
在那之后,我还有另一个函数叫做do_Scan()
它扫描表并对其进行一些处理和索引。
但是,我希望这个函数do_Scan() 以一定的时间间隔运行,比如说每 N 分钟然后它会调用这个函数。 N 绝对是可配置的。
我正在考虑使用计时器类,但不太确定如何实现配置。我的想法是创建一个 Timer 函数,该函数将调用 do_Scan 方法。
类应该是这样的:
public void schedule(TimerTask task,long delay,long period){
}
我的主要方法:
public static void main(String[] args) throws Exception {
Indexing test= new Indexing();
java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
// Exception e=e.printStackTrace();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file path: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
if(file.exists() && !file.isDirectory()) {
test.index_request(filename,"Active",date,date,"");
}else{
test.index_request(filename,"Error",date,date,"Some errorCode");
}
// Call schedule() function
}}
如何设置 Timer 类,使其在特定时间间隔内无限期运行?
【问题讨论】:
-
例子?但我希望定时器在它自己的功能中
-
stackoverflow.com/questions/11416242/… 看看这对你有没有帮助
-
是的,它确实有帮助。这是最好的方法吗?
-
建议
Runnable的答案已经很老了。改用 lambdas(从 java 1.8 开始)。
标签: java