Reputation: 6290
I need a way to have a timer that is running on start command. Initially, the timer will be told how long to run for. However, i need a way to change this mid-way in between. If a user specifies that they would like to change the time the timer runs (by either decreasing, increasing or even ending the timer all together). I also want to be able to update the UI by showing the current time in minutes:seconds format.
The user may also want to spawn multiple timers - so they should have a way of monitoring and accessing different timers which they have set..
Currently this is what i have - from what i can tell, it works.. but i don't feel too good about it :S how can i make this better? Or what is the right way of doing this? Keep in mind that there will be other things happening while this timer is running - for instance, the user may be interacting with the UI and executing different commands un-related to the timer..
I really don't know much about threads or threading... so this is relatively new to me..
thanks in advance!
In Main:
//every time they request for a new timer, i will instantiate a new Task object..
Task task = new Task();
task.run()
task.getTaskTime();
Task.java:
public class Task extends Thread{
@Override
public void run()
{
timer = new Timer(60 * 60);
timer.start();
}
public boolean getTImerRunning() {
return timer.timerRunning;
}
public double getTaskTime() {
return timer.currentTime;
}
}
In Timer.java:
public class Timer extends Thread {
public static final int DEFAULT_TIMER = 180;
private long startMinute = 0;
private int _timer;
public double currentTime = 0;
public boolean timerRunning = true;
Timer(int timer) {
this._timer = timer;
}
Timer() {
this._timer = DEFAULT_TIMER;
}
@Override
public void run(){
long start = System.currentTimeMillis();
startMinute = start;
while(elapsedTime() <= this._timer) {
currentTime = elapsedTime();
}
timerRunning = false;
}
/**
* Return elapsed time since this object was created.
*/
private double elapsedTime() {
long now = System.currentTimeMillis();
return (now - startMinute);
}
}
Upvotes: 2
Views: 75
Reputation: 1709
Every time the user creates a "timer", do not create a new Task, but create an object MyTimer that holds the creation time and countdown duration and add the instance to an ArrayList.
The very first and only the first time, a user creates a timer you will create a task that executes every second. When that task executes it updates the UI and cycles through the ArrayList and updates each instance of MyTimer by adjusting the countdown duration.
That should keep things simple and reduce overhead.
Good Luck!
Upvotes: 1