26 java scheduling
我不是专家,只是初学者.所以我恳请你为我写一些代码.
如果我有两个班,CLASS A和CLASS B了,里面CLASS B有一个叫功能funb().我想CLASS A每隔十分钟调用一次这个函数.
你已经给了我一些想法,但我不太明白.
你能发布一些示例代码吗?
Tim*_*Tim 27
这是一个带有方法的类,该方法将ScheduledExecutorService设置为每隔十秒钟发出一小时的哔声:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
Run Code Online (Sandbox Code Playgroud)
Phi*_*ere 15
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class ClassExecutingTask {
long delay = 10 * 1000; // delay in milliseconds
LoopTask task = new LoopTask();
Timer timer = new Timer("TaskName");
public void start() {
timer.cancel();
timer = new Timer("TaskName");
Date executionDate = new Date(); // no params = now
timer.scheduleAtFixedRate(task, executionDate, delay);
}
private class LoopTask extends TimerTask {
public void run() {
System.out.println("This message will print every 10 seconds.");
}
}
public static void main(String[] args) {
ClassExecutingTask executingTask = new ClassExecutingTask();
executingTask.start();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 12
试试这个.它会在每个分钟内重复run()函数.要更改设置分钟,请更改MINUTES变量
int MINUTES = 10; // The delay in minutes
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() { // Function runs every MINUTES minutes.
// Run the code you want here
CLASSB.funcb(); // If the function you wanted was static
}
}, 0, 1000 * 60 * MINUTES);
// 1000 milliseconds in a second * 60 per minute * the MINUTES variable.
Run Code Online (Sandbox Code Playgroud)
别忘了做进口!
import java.util.Timer;
import java.util.TimerTask;
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请转到此处:
http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html