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);
Related
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);
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...
public void myMethod()
{
if (capture.isOpened()) {
while (true) { //This is The main issue.
capture.read(webcam_image);
if (!webcam_image.empty()) {
webcam_image = my_panel.detect(webcam_image);
temp = my_panel.matToBufferedImage(webcam_image);
my_panel.setimage(temp);
my_panel.repaint();
System.out.print("."); // It should prints "." but the above code doesn't works.
} else {
System.out.println(" --(!) No captured frame -- Break!");
break;
}
}
}
}
This is invoking code of the above method...
actually it's an ActionEvent which can be fire on menu is clicked.
if (e.getActionCommand().equals("goLive")) {
System.out.println("Live...");
myMethod();
}
I know actually it's problem of the infinite while loop but here I need to put this condition at any cost.
The exact solution for this type of problem is Timer class. We can overcome this issue using the following code.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
myMethod();
}
}, 0);
Thanks google, oracle and java doc
Assuming that myMethod is called by an event listener (actionPerformed), the infinite loop is blocking the event dispatch thread.
You can avoid this by using SwingWorker or executing your loop on another thread:
public void myMethod()
{
if (capture.isOpened()) {
new Thread(new Runnable() { //Create a new thread and pass a Runnable with your while loop to it
#Override public void run() {
while (true) {
capture.read(webcam_image);
if (!webcam_image.empty()) {
webcam_image = my_panel.detect(webcam_image);
temp = my_panel.matToBufferedImage(webcam_image);
SwingUtilities.invokeLater(new Runnable() { //The following lines affect the GUI and must be executed on the event dispatch thread, so they should be wrapped inside a Runnable
#Override public void run() {
my_panel.setimage(temp);
my_panel.repaint();
}
}
try{
Thread.sleep(xxx); //consider waiting for a moment (e.g. 16ms)
} catch(InterruptedException e) { ... }
System.out.print(".");
} else {
System.out.println(" --(!) No captured frame -- Break!");
break;
}
}
}
}).start(); //Let the thread loop in the background
}
}
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.
I want to run a thread (Which does some time consuming task in background and does NOT update UI) it just downloads some files form the internet and it is independent from the UI.
I want to run this thread repeatedly after some time interval.
How can i do this, I have thread something like below:
boolean mResult =false;
void onCreate()
{
DownloadThread mDownloadThread = new DownloadThread();
mDownloadThread.start();
}
class DownloadThread extends Thread implements Runnable
{
public void run()
{
// My download code
mResult = result;
}
}
Do i need to use Handler for implementing this?
Option 1:
volatile boolean flag = true;
public void run()
{
while(flag)
{
// Do your task
try{
Thread.Sleep(interval);
} catch(Exception e){
}
}
}
Option 2:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Do your task
}
}, 0, interval);
Option 3:
volatile boolean flag = true;
public void someMethod(){
// Do your task
try{
Thread.Sleep(interval);
} catch(Exception e){
}
if(flag)
return;
else
someMethod();
}
Option 4:
final Handler handler = new Handler();
volatile boolean flag = true;
Class A implements Runnable{
public void run(){
// Do your Task
}
if(!flag)
handler.postDelayed(a, interval);
}
A a = new A();
handler.postDelayed(a);
There will be many more options. I never tried option 3 and 4. It just came to my mind and I wrote. If I were you I would use any of 1 or 2.
Prefered choice is
java.util.concurrent.ScheduledExecutorService
Newer and robust implementation, More here ScheduledExecutorService
I would use a Timer to achieve this. Try this:
void onCreate()
{
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Download your stuff
}
}, 0, 1000);
}
It starts immediately and the run-Method gets called every second.