Husnain
Husnain

Reputation: 137

Can I run timer at different intervals of time?

Actually i wanted to ask can i give value from database to a timer delay?

    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 at myDelay, can i give different values through database? Or it must be fixed?

Upvotes: 4

Views: 291

Answers (2)

user1506104
user1506104

Reputation: 7086

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

schedule(TimerTask task, long time)

Everytime you have a new time from DB, just create a new Timer() like so

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

The good thing about this is you don't have to cancel the timer every single time because it is meant to run once.

Upvotes: 1

Shubham Gangpuri
Shubham Gangpuri

Reputation: 431

May you should change your approach to the problem, create a function to return the 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());

This should work for what you want to achieve...

Upvotes: 0

Related Questions