Can I start a timer at different time intervals?

Actually, I wanted to ask if I can give a value from the database to delay the timer?

    Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                  // whatever
                    }
                }
            });
        }
    };
    timer.schedule(timerTask,2000,**myDelay**); //here at my delay

Here on myDelay, can I give different values ​​through the database? Or should it be fixed?

+4
source share
2 answers

If you want to change the time all the time with different values, I suggest you use

schedule(TimerTask task, long time)

Every time you have a new time from the database, just create a new one Timer(), for example,

time = getNewTimeFromDB();
createNewTask(time);
....
private void createNewTask(long time) {
    Timer timer=new Timer();
    TimerTask timerTask=new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // whatever
                }
            });
        }
    };
    timer.schedule(timerTask,time);
}

It's good that you do not need to cancel the timer every time, because it is designed to run once.

+1
source

Can you change your approach to the problem, create a function to return time from the database FunctionToGetDelayFromDB();

Timer timer=new Timer();
long time = FunctionToGetTimeFromDB();
TimerTask timerTask=new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                    // whatever
                    timer.schedule(timerTask, System.currentTimeMillis() + FunctionToGetDelayFromDB());
                }
            }
        });
    }
};
timer.schedule(timerTask, System.currentTimeMillis() + FunctionToGetDelayFromDB());

, ...

0

Source: https://habr.com/ru/post/1686735/


All Articles