Reputation: 291
I have to run a job using a thread for every 1 hour. This job is to read files in a folder. I have created a simple thread
Thread t = new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000*60*60);
//Implementation
} catch (InterruptedException ie) {
}
}
}
};
t.start();
which runs every one hour so that I can call the function to read the files. I want to know if this approach is good or any other approach is good
Upvotes: 2
Views: 2605
Reputation: 1813
import java.util.Timer;
import java.util.TimerTask;
public class MyTimer {
public static void main(String[] args) {
OneHourJob hourJob = new OneHourJob();
Timer timer = new Timer();
timer.scheduleAtFixedRate(hourJob, 0, 5000 * 60 * 60); // this code
// runs every 5 seconds to make it one hour use this value 5000 * 60 *
// 60
}
}
class OneHourJob extends TimerTask {
@Override
public void run() {
System.out.println("Ran after one hour.");
}
}
Above code runs every five seconds. Whatever work you need to do write that code in run method of OneHourJob
Upvotes: 1
Reputation: 801
You can use ScheduledExecutorService for this task, and here is a Sample Example
Upvotes: 2
Reputation: 20741
If you want to use just Thread
then try
try {
Thread.sleep(1000 * 60 * 60);
} catch (InterruptedException ex) {}
otherwise its a good choice that you can go with ScheduledExecutorService
ScheduledExecutorService executor = ...
executor.scheduleAtFixedRate(someTask, 0, 1, TimeUnit.HOUR);
Upvotes: 0