简体   繁体   English

具有多个超时的Java计时器

[英]Java timer with multiple timeouts

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. 我想创建一个计时器,该计时器最多计数3.5秒,如果毫秒计数等于数组的元素之一,则调用相同的函数。 Is there a way to do this shortly without making multiple timers ? 有没有一种方法可以在不使用多个计时器的情况下立即完成此操作?

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");
    }
}

Subclassing a regular java.awt.Timer . 子类化一个常规的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. 还没有测试过,希望它能工作。

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);
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM