我有一个我想在每15分钟后运行一次的线程。目前我从另一个类调用此线程,如
Class B{
public void start(){
while(true){
new Thread(new A()).start();
}
}
}
Class A implements Runnable{
@override
public void run(){
//some operation
}
}
如何每15分钟调用一次线程A.
答案 0 :(得分:4)
您可以使用Timer
或ScheduledExecutorService
以一定间隔重复任务。
ExecutorService
可以安排命令在给定延迟后运行,或定期执行。
示例代码:
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
}, 0, 15, TimeUnit.MINUTES);
答案 1 :(得分:3)
答案 2 :(得分:2)
像这样使用睡眠:
public void run(){
while(true){
// some code
try{
Thread.sleep(15*60*1000) // sleep for 15 minutes
}
catch(InterruptedException e)
{
}
}
}
答案 3 :(得分:2)
备用选项使用课程java.util.Timer
Timer time = new Timer();
ScheduledTask st = new ScheduledTask();
time.schedule(st, 0, 15000);
或
public void scheduleAtFixedRate(TimerTask task,long delay,long period);
甚至
java.util.concurrent.ScheduledExecutorService
的方法
schedule(Runnable command, long delay, TimeUnit unit)
答案 4 :(得分:0)
启动后无法重新开始。
您可以将Thread.Sleep(15*60*1000)
放入run
函数中,以使其进入睡眠状态并将其包围,以便再次循环播放。
答案 5 :(得分:0)
我认为Timer
会做你的。
import java.util.Timer;
import java.util.TimerTask;
class A extends TimerTask {
@Override
public void run(){
//some operation
}
}
A task = new A();
final long MINUTES = 1000 * 60;
Timer timer = new Timer( true );
timer.schedule(task, 15 * MINUTES, 15 * MINUTES);