Search code examples
javaandroidrandomtimertimertask

How to schedule a random timing (every random minutes) event


I'm developing an Android App, I'm trying to manage a Vibration event. I need to schedule it every random minutes when a switch is checked. I have been using this code:

int delay3 = (60 + new Random().nextInt(60)) * 1000;

timer3.schedule(timerTask3, 0, delay3);

but the timer doesn't change delay3 until the switch is unchecked and checked again. Is there a way to schedule the event at random timing i.e. delay3 should change every time the task is running without unchecking the switch?

Thank you.


Solution

  • Schedule the task to run after a random delay once. Inside the task, after the desired process, reschedule it after a random delay.

    Example:

    Random random = new Random();
    Timer timer = new Timer();
    timer.schedule(new MyTimerTask(timer, random), random.nextInt(10000));
    

    with:

    private static class MyTimerTask extends TimerTask {
        private final Timer timer;
        private final Random random;
    
        public MyTimerTask(Timer timer, Random random) {
            this.timer = timer;
            this.random = random;
        }
    
        @Override
        public void run() {
            System.out.println("TEST");
            timer.schedule(new MyTimerTask(timer, random), random.nextInt(10000));
        }
    }