I'm writing an application in Java, but need to know how to subtract from a variable once every second. What's the easiest way to do this? Thanks!
The name of the very Java class you need to use to do repeating operations is already sitting there in one of your tags! ;)
class YourTimer extends TimerTask
{
public volatile int sharedVar = INITIAL_VALUE;
public void run()
{
--sharedVar;
}
public static void main(String[] args)
{
Timer timer = new Timer();
timer.schedule(new YourTimer(), 0, 1000);
// second parameter is initial delay, third is period of execution in msec
}
}
Remeber that Timer
class is not guaranteed to be real-time (as almost everything in Java..)
While the Timer
class will work, I recommend using a ScheduledExecutorService
instead.
While their usage is extremely similar, ScheduledExecutorService
is newer, more likely to receive ongoing maintenance, fits in nicely with other concurrent utilities, and might offer better performance.
What are you trying to achieve? I would not try relying on the timer to properly fire exactly once per second. I would simply record the start time, and whenever a timer fires, recalculate what the value of the variable should be. Here's how I would do it...
class CountdownValue {
private long startTime;
private int startVal;
public CountdownValue(int startVal)
{
startTime = System.currentTimeMillis();
}
public int getValue()
{
return startVal - (int)((System.currentTimeMillis() - startTime)/1000);
}
}