I have a program where I am able to insert a filepath and it's corresponding parameters to a table.
After that, I have another function called do_Scan()
that scans the table and do some processing and indexing to it.
However, I want this function do_Scan()
to be run at certain intervals, say every N minutes then it will call this function. The N is definitely configurable.
I was thinking of using a timer class but not quite sure how to implement the configuration. The idea is I create a Timer function that will call the do_Scan
method.
The class should be something like this:
public void schedule(TimerTask task,long delay,long period){
}
My main method:
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
}}
How do I setup the Timer class so it runs indefinitely for certain interval?
Calling run() Method Multiple TimesBy using a for loop, we can call the same run method numerous times. Example: Java.
An interval in Joda-Time represents an interval of time from one millisecond instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.
The simplest way is using a class which is a part of standard library.
java.util.Timer
Here is a simple example of using it:
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With