运行 在 java 个线程中每隔一小时一个作业
Run a job for every one hour in java thread
我必须 运行 每 1 小时使用一个线程的作业。这项工作是读取文件夹中的文件。我创建了一个简单的线程
Thread t = new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000*60*60);
//Implementation
} catch (InterruptedException ie) {
}
}
}
};
t.start();
每隔一小时 运行s,这样我就可以调用函数来读取文件。我想知道这个方法好还是其他方法好
您可以使用ScheduledExecutorService for this task, and here is a Sample Example
如果你只想使用 Thread
那么试试
try {
Thread.sleep(1000 * 60 * 60);
} catch (InterruptedException ex) {}
否则你可以选择 ScheduledExecutorService
ScheduledExecutorService executor = ...
executor.scheduleAtFixedRate(someTask, 0, 1, TimeUnit.HOUR);
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.");
}
}
以上代码每五秒 运行s。无论您需要做什么工作,请在 OneHourJob
的 运行 方法中编写该代码
我必须 运行 每 1 小时使用一个线程的作业。这项工作是读取文件夹中的文件。我创建了一个简单的线程
Thread t = new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000*60*60);
//Implementation
} catch (InterruptedException ie) {
}
}
}
};
t.start();
每隔一小时 运行s,这样我就可以调用函数来读取文件。我想知道这个方法好还是其他方法好
您可以使用ScheduledExecutorService for this task, and here is a Sample Example
如果你只想使用 Thread
那么试试
try {
Thread.sleep(1000 * 60 * 60);
} catch (InterruptedException ex) {}
否则你可以选择 ScheduledExecutorService
ScheduledExecutorService executor = ...
executor.scheduleAtFixedRate(someTask, 0, 1, TimeUnit.HOUR);
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.");
}
}
以上代码每五秒 运行s。无论您需要做什么工作,请在 OneHourJob
的 运行 方法中编写该代码