gpt4 book ai didi

java-每隔一段时间调用一个函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:46:08 24 4
gpt4 key购买 nike

我有一个程序,我可以在其中插入文件路径及其与表的对应参数。

在那之后,我有另一个函数叫做 do_Scan()扫描表并对其进行一些处理和索引。

但是,我希望此函数 do_Scan() 以特定的时间间隔运行,比如每 N 分钟一次,然后它将调用此函数。 N 绝对是可配置的。

我正在考虑使用计时器类,但不太确定如何实现配置。我的想法是创建一个调用 do_Scan 方法的 Timer 函数。

类应该是这样的:

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 类,使其在特定时间间隔内无限期运行?

最佳答案

最简单的方法是使用属于标准库的类。

java.util.Timer

这是一个简单的使用示例:

import java.util.Timer; 
import java.util.TimerTask;

class MyTask extends TimerTask
{
public static int i = 0;
public void run()
{
System.out.println("Hello, I'm timer, running iteration: " + ++i);
}
}

public class Test
{
public static void main(String[] args)
{

Timer timer = new Timer();
TimerTask task = new MyTask();

timer.schedule(task, 2000, 5000); // 2000 - delay (can set to 0 for immediate execution), 5000 is a frequency.

}
}

关于java-每隔一段时间调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53512829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com