Reputation: 1163
Let's say I have an array of integers
int timeouts [] = {1000 , 2000 , 3000 , 3500};
and I want to create a timer which counts up to 3.5 second and calls the same function if the milisecond count equals to one of the elements of the array. Is there a way to do this shortly without making multiple timers ?
Upvotes: 1
Views: 396
Reputation: 16234
Subclassing a regular java.awt.Timer
.
public class VariableTimer extends Timer{
private int [] millis;
private counter = 0;
public VariableTimer(int[] millis, ActionListener l) {
super(millis[0], l);
this.millis = millis;
}
@Override
protected void fireActionPerformed(ActionEvent e) {
super.fireActionPerformed(e);
setDelay(millis[++counter%millis.length]);
restart();
}
}
Haven't tested it, hope it works.
Upvotes: 0
Reputation: 812
public class Timer {
static final int timeouts [] = {1000 , 2000 , 3000 , 3500};
private static int findMax(int [] array) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
private static void checkIfContained(double number) {
for (int i : timeouts) {
if ((double) i == number) {
System.out.println("SUCCESS!");
// TODO
}
}
}
public static void main(String[] args) throws InterruptedException {
int max = findMax(timeouts);
double counter = 0.0;
while (counter < max) {
Thread.sleep(3500);
counter += 3.5;
checkIfContained(counter);
}
}
}
Upvotes: 0
Reputation: 6939
public class ArraysFun{
private static int[] timeouts = {1000,2000,3000,3500};
public static void main(String[] sss){
endlessCounter(0);
}
//Endless counter that calls your function
public static void endlessCounter(int i){
long start = System.currentTimeMillis();
long now;
do{
now = System.currentTimeMillis();
//checks to see if the time was elapsed
}while(now - start<timeouts[i]);
//call your function
callFunction(i);
//iterate through the timeouts array
i = (i>= timeouts.length-1)? 0 : i+1;
//call the counter again
endlessCounter(i);
}
//just print which is the timeout that was waited before this call
private static void callFunction(int i) {
double duration = (double)timeouts[i]/1000.00;
System.out.println("Function called after "+ duration + " seconds");
}
}
Upvotes: 1