How to make something happen at fixed intervals of time in a java program?
Basically, I have an int value, x, that is an instance variable of a class. It is set to 0 initially. I have another method, "getNum," that increments and returns x. This getNum() method is called by an outside program. However, each day (let's say, at midnight, for simplicity's sake) I want to reset x to 0. How would this be done? The problems I'm having now: Date(int, in开发者_如何学JAVAt, int) is deprecated but the method only takes Dates, not Calendars; the TimerTask event never happens; every time I run the program at the bottom, it simply prints "0" every time even though the number should not be constantly resetting. Basically, nothing works. Any ideas what is going wrong?
import java.util.*;
class Foo {
private static void scheduleTimer() {
Timer timer = new Timer();
long c = 86400000;
timer.scheduleAtFixedRate(new MyTimerTask(),
new Date(2011, 7, 31), c);
}
public static int getNum() { return x++; }
private static int x = 0;
public static void resetNum() { x = 0; }
}
class MyTimerTask() extends TimerTask {
public void run() {
Foo.resetNum();
}
public class Bar { // in a separate file
public static void main (String[] args) {
System.out.println(Foo.getNum());
}
}
Fix your two compilation errors, call Foo.scheduleTimer() somewhere to actually start the timer, give the timer a reasonable delay and period (like a few seconds), and then call Foo.getNum() repeatedly instead of just once. For example:
import java.util.Timer;
import java.util.TimerTask;
public class Foo {
public static void scheduleTimer() {
Timer timer = new Timer();
long c = 3000;
timer.scheduleAtFixedRate(new MyTimerTask(), c, c);
}
public static int getNum() { return x++; }
private static int x = 0;
public static void resetNum() { x = 0; }
}
class MyTimerTask extends TimerTask {
public void run() {
Foo.resetNum();
}
}
class Bar {
public static void main(String[] args) throws Exception {
Foo.scheduleTimer();
while (true) {
System.out.println(Foo.getNum());
Thread.sleep(1000);
}
}
}
Per the documentation for scheduleAtFixedRate(TimerTask, Date, long)
:
Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.
So it would take roughly 86400000 milliseconds for your task to be called. Are you actually waiting that long to confirm it is not working?
精彩评论