1

Right now I have a timer that has a delay of 5 seconds, however I need a different delay after it has run once. I am going through some pictures and during the first round it should show them for 5 seconds. After that it should show them for 10 seonds. How is it possible to change the delay of a Timer during runtime?

What has to happen:

  • Start Timer
  • Run for 5 seconds
  • Change delay
  • Run for 10 seconds
Thorsten S.
  • 4,144
  • 27
  • 41

2 Answers2

0

Try to add some code!

You need to check if the timer has 5 seconds make it 10 and so on.

int delayTime = 5;
//run first delay
if (delayTime == 5){
delayTime = 10;
}

This is some code for the idea, don't know how it looks in your project.

JP..t
  • 575
  • 1
  • 6
  • 28
0

There can be two approach for your use case:

First Approach:

Like say I want to show the picture for 1000 seconds. So I will execute for loop till 1000 seconds; or if you want to run it infinitely then you can change the condition in for loop. Below code will execute the for loop after every 5 seconds delay.

int delayTimeInMiliSec;
    for(int delayTime = 5 ; delayTime<=1000; delayTime = delayTime+5){
        delayTimeInMiliSec = delayTime * 1000;
        // here Call your method that shows pictures
        Thread.sleep(delayTimeInMiliSec);
    }

Second Approach:

  1. create a class extending TimerTask(available in java.util package). TimerTask is a abstract class.
  2. Write your code in public void run() method that you want to execute periodically.

Code sample:

  import java.util.TimerTask;

    // Create a class extends with TimerTask
    public class ScheduledTask extends TimerTask {

        // Add your task here
        @Override
        public void run() {
            //show pictures code
        }
    }

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {

        Timer time = new Timer(); // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 5000); // Create Repetitively task for every 5 secs


    }
}
Reena Upadhyay
  • 1,977
  • 20
  • 35