Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java- Calling a function at every interval

Tags:

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?

like image 508
Daredevil Avatar asked Nov 28 '18 05:11

Daredevil


People also ask

How do you call a method continuously in Java?

Calling run() Method Multiple TimesBy using a for loop, we can call the same run method numerous times. Example: Java.

What is interval in 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.


1 Answers

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.

   } 
} 
like image 142
Mark Bramnik Avatar answered Oct 05 '22 01:10

Mark Bramnik