Can I run timer at different intervals of time? - java

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?

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.

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...

Related

Restarting Java timer with a different time interval

I'm working on creating a timer in Java, and was wondering how I can use timer.cancel to then create a new timer which has a different interval.
My code looks something like this:
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
gameView.invalidate();
// timer.cancel(); - here, need to somehow restart timer with new interval
}
});
}
}, 0, TimerInterval.interval);
In another view, I'm modifying TimerInterval.interval, but this doesn't do anything/update the timer, because I need to somehow completely cancel the timer and create a new one, but I'm not sure how to do this.
Any help with this matter would be appreciated.

Timer can not be repeated on android How to fix?

I want Timer execute repeat.
so I try this source
public static void init() {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
Looper.prepare();
recordWork();
Looper.loop();
}
};
Timer timer = new Timer();
timer.schedule(timerTask, 1000, 30000);
}
init() called when record button click.
why recordWork() only one execute?
this timer not execute repeat.
How to fix this problem?
thanks.
Use the function timer.scheduleAtFixedRate() to execute the timer every X seconds.
For example timer.scheduleAtFixedRate(timerTask, new Date(), 2000) to start the timer now and execute every 2 seconds.
Use it like below
public static void init() {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
Looper.prepare();
recordWork();
Looper.loop();
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 1000, 30000);
}
Use Timer as a global variable. and cancel it its need done.
if(timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
If you still can't fix your Timertask. Might as well give CountDownTimer a try
https://developer.android.com/reference/android/os/CountDownTimer.html
public void startCountDown() {
countDownTimer = new CountDownTimer(totalTimeinMillis,intervalBetweenCountdown) {
#Override
public void onTick(long millisUntilFinished) {
//execute repeating task here
}
#Override
public void onFinish() {
}
};
}
Use handler
Handler handler = new Handler();
int delay = 2000; //milliseconds
handler.postDelayed(new Runnable(){
public void run(){
recordWork();
handler.postDelayed(this, delay);
}
}, delay);

How to display window just one time in java Timer

I have a Timer in my app. Timer connects and disconnects database every 10 sec. This is just to know when my db is unreacheble. Maybe there are other ways. But I did so.
How to display the alert window once to successfully connect and bring back with repeated tripping?
Thanks any help!
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Platform.runLater(new Runnable() {
public void run() {
SqlTransport.openConnectionToDB();
System.out.println("connect");
if (SqlTransport.openConnectionToDB() == false) {
alertWindow.display();
caseCount.setVisible(false);
System.out.println("noConnection");
}else {
System.out.println("connectDone");
caseCount.setVisible(true);
caseCount.setText(String.valueOf(SqlTransport.getOpenedCount()));
pause.playFromStart();
pause.setOnFinished(e -> {
SqlTransport.closeConnectionToDB();
System.out.println("closeDone");
});
}
}
});
}
}, 10000, 10000);
Add a boolean field to your TimerTask which indicates if the connection worked last time it was checked. Set the field appropriately every time the task runs. Only display the window if there was a connection last time.
EDIT: here's some code, try it out.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
// It's possible that a starting value of false will
// match your desired behaviour better.
// Experiment with a situation where there is no connection initially.
boolean previouslyConnected = true;
public void run() {
Platform.runLater(new Runnable() {
public void run() {
SqlTransport.openConnectionToDB();
System.out.println("connect");
boolean connected = SqlTransport.openConnectionToDB();
// ! means 'not'. This is typically written instead of 'connected == false'
if (!connected) {
if (previouslyConnected) {
alertWindow.display();
}
caseCount.setVisible(false);
System.out.println("noConnection");
} else {
System.out.println("connectDone");
caseCount.setVisible(true);
caseCount.setText(String.valueOf(SqlTransport.getOpenedCount()));
pause.playFromStart();
pause.setOnFinished(e -> {
SqlTransport.closeConnectionToDB();
System.out.println("closeDone");
});
}
previouslyConnected = connected;
}
});
}
}, 10000, 10000);

Java timer.cancel() not stopping timer

I'm a novice at Java, and I've been trying to use java.util.timer to reset an existing timer after taking the right command input.
However, I've been unable to cancel the timertask properly, so the timer thread runs multiple instances of the timertask if the method is called multiple times. Any help would be appreciated.
Edit: I've changed the location of new Timer(), but it doesn't seem to have fixed it.
Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
public static void main (String[] args) {
Timer timer = new Timer();
while (true) {
//BufferedReader to read input
//Something
if (input[0].equals("r")) {
time t = new time();
time.RestartTimer();
}
}
}
public void RestartTimer() {
ttimer.cancel();
timer.cancel();
Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}
This is happening because you are creating a new instance of time class (time t = new time(); ) inside the while loop. Instead do this :
public static void main (String[] args) {
time t = new time(); // create an instance of time class
while (true) {
//Something
if (input[0].equals("r")) {
// call RestartTimer on the same in
t.RestartTimer();
}
}
}
Also inside RestartTimer() function you are creating new instance of Timer. Change it as follows :
public void RestartTimer() {
ttimer.cancel();
timer.cancel();
timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}
time.RestartTimer(); statement won't be called until and unless either you change the modifier of method or call this method by using static object in main method. I think this is the only reason that your timer is not getting update.

How to start a thread after specified time delay in java

I have called a method in ServletContextListener as thread ..Now as per my need i have to delay the thread for 1 minutes and then start executing the method called in the thread but i am not able to do that as i am very new in this...
Here is my code ...
public class Startup implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
public void contextInitialized(ServletContextEvent sce) {
// Do your startup work here
System.out.println("Started....");
//captureCDRProcess();
new Thread(new Runnable() {
#Override
public void run() {
captureCDRProcess();
}
}).start();
}
Please help me ..
Thanks in advance..
To do this properly, you need to use a ScheduledThreadPoolExecutor and use the function schedule like this:
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);
executor.schedule(new Runnable() {
#Override
public void run() {
captureCDRProcess();
}
}, 1, TimeUnit.MINUTES);
Thread.sleep is not the way to go, because it does not guarantee that it wakes up after a minute. Depending on the OS and the background tasks, it could be 60 seconds, 62 seconds or 3 hours, while the scheduler above actually uses the correct OS implementation for scheduling and is therefore much more accurate.
In addition this scheduler allows several other flexible ways to schedule tasks like at a fixed rate or fixed delay.
Edit: Same solution using the new Java8 Lamda syntax:
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);
executor.schedule(() -> captureCDRProcess(), 1, TimeUnit.MINUTES);
Or you can delay creating the thread with Timer and TimerTask:
public void contextInitialized() {
// Do your startup work here
System.out.println("Started....");
Timer timer = new Timer();
TimerTask delayedThreadStartTask = new TimerTask() {
#Override
public void run() {
//captureCDRProcess();
//moved to TimerTask
new Thread(new Runnable() {
#Override
public void run() {
captureCDRProcess();
}
}).start();
}
};
timer.schedule(delayedThreadStartTask, 60 * 1000); //1 minute
}
Have a look at Thread.sleep(). Maybe add it to the new thread's run method, so that it sleeps the needed time before doing any meaningful work.
You can start thread and inside the thread use sleep method for one minute.
ScheduledThreadPoolExecutor has this ability, but it's quite heavyweight.
Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):
public class JavaUtil {
public static void postDelayed(final Runnable runnable, final long delayMillis) {
final long requested = System.currentTimeMillis();
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
long leftToSleep = requested + delayMillis - System.currentTimeMillis();
if (leftToSleep > 0) {
Thread.sleep(leftToSleep);
}
break;
} catch (InterruptedException ignored) {
}
}
runnable.run();
}
}).start();
}
}
Test:
#Test
public void testRunsOnlyOnce() throws InterruptedException {
long delay = 100;
int num = 0;
final AtomicInteger numAtomic = new AtomicInteger(num);
JavaUtil.postDelayed(new Runnable() {
#Override
public void run() {
numAtomic.incrementAndGet();
}
}, delay);
Assert.assertEquals(num, numAtomic.get());
Thread.sleep(delay + 10);
Assert.assertEquals(num + 1, numAtomic.get());
Thread.sleep(delay * 2);
Assert.assertEquals(num + 1, numAtomic.get());
}

Categories

Resources