How can I implement a timer in Java 8? I prefer one simple method for this. I want to do something every 15 min or 30 min. Any idea?
you can use
Thread.sleep(milliseconds)
call the function you want and put it inside Runnable .
Example :
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3000); // 3
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//your Function
}
});
}
}).start();
OR
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}});
t.start();
Related
i am generating a random string for infinite time and setting it to a EditText.
when i was not using runOnUi app was working on newer devices which have high capability. but it crashes on older model when i start the thread and gave error(called from wrong thread exception)
Then i used runOnUi but it makes the super slow and force close it.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
tryPass.setText(getAlphaNumericString());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
});
thread.start();
You're trying to block UI thread by calling Thread.sleep(2000); on UI thread.
Try this way:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
tryPass.setText(getAlphaNumericString());
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
i'm trying to make a delay inside while loop using Thread.sleep() method . here is my code :
new Thread(new Runnable() {
#Override
public void run() {
z=0;
while (z<45){
z++;
handler.post(new Runnable() {
#Override
public void run() {
time.setText(Integer.toString(45-z));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
this code was working and suddenly a problem occurred . it started to make a delay less than one minute , sumtimes 500 ms and sumtimes less than that
Instead if using a different thread, Thread.sleep(), Handler and while loop you can try only with Handler like this,
private int timerCount = 0;
private static Handler myHandler = new Handler();
private void runVVRunnable() {
myHandler.postDelayed(runnable, 1000);
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
timerCount++;
if ((time == null)) {
return;
}
if (timerCount <= 45) {
time.setText(Integer.toString(timerCount));
runVVRunnable();
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
myHandler.removeCallbacks(runnable);
}
you can just call runVVRunnable() it will do the same process which you are doing while loop
Just a guess but when sleeping/waiting on Java thread you need to try-catch InterruptedException.
This exception is thrown when "someone" calls interrupt() on your thread.
This will cause the thread to wake up from sleep early than expected.
Check if you catch InterruptedException before your thread terminated.
I need stop thread and handler when my progress bar reaches 0 from 100 when thread runs the progress bar reaches but the progressStatus value going in negative please help me to stop thread after progress bar reaches 0
new Thread(runn =new Runnable() {
public void run() {
while (progressStatus <= 100) {
progressStatus += doWork();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i=-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
}
}
});
}
}
private int doWork() {
return i;
}
}).start();
your program is not thread safe, you actually reading and writing a variable (progressStatus) from two different threads, you must avoid doing that or if you want to do that you must use synchronized block. In order to solve your problem you can do this way:
Thread t;
progressStatus = 100;
t = new Thread(runn =new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
progressStatus=progressStatus-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
t.interrupt();
}
}
});
another way that i recommend you is using ScheduledThreadPoolExecutor with the function scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit). something like:
final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
myTimer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable(){
#Override
public void run(){
}
});
}
}
}, 0,10, TimeUnit.MILLISECONDS);
and in order to close it use myTimer.shutdownNow();
I want to update the text of a notification every second. i wrote this code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Text");
builder.setContentText("value updated every 1 second");
}
}
}, 1*1000);
but the value is not updated every 1 second but only one time. why? how can i do this?
Try to use Timers Handler ll invoke one time.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
updateUI();
}
};
timer.scheduleAtFixedRate(task, 0,1000);
put your Handler to separate method
public void updateUI(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Text");
builder.setContentText("value updated every 1 second");
}
}, 1000);
}
his code starts an thread which sleeps 1000 milliseconds every round.
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// update TextView here!
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
String move=jTextField1.getText();
i=Integer.parseInt(move);
timer = new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
i--;
if(i<=0)
{
if(move.equals("0"))
{
Thread th=new Thread(new DetectImage());
th.start();
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new TrafficMainGUI(storeValue);
}
});
}
timer.stop();
}
}
jTextField1.setText(""+i);
}
});
timer.start();
move=""+i;
//Thread th in DetectImage class
public void run()
{
while(stay<20)
{
try {
stay++;
//few contions
Thread.sleep(1000);
}
}
}
//EveryThing is working fine with thread but when i use SwingUtiities.invokeLater()
to call the same class in which this code is there for getting infinite condition.
This doesnot redirect it to the class TrafficMainGUI.Is there some other method to achieve this kind of model.
jTextField1.setText(""+i); must be wrapped in invokeLater for this job by invoked from util.Timer
use Swing Timer instead
if(move.equals("0")) { is about animations, then to use Swing Timer exclusivelly