I want to check if an int value is higher than 20 for a certain amount of 15 minutes, if that int value stays higher than 20 in those 15 minutes, code will executed
I didn't understand the difference between a Handler and a Runnable, how to use them, What do they do...
My question is:
How can I run an if statement for a certain time using a Runnable/Handler
This is the if statement which I want to be checked for 15 mins,
if(Speed > 20){
// Code that will run after 15 mins IF the speed is higher than 20 for all that time
}
add this, this timer will execute after 1 sec you can add your time you want and put your if statement inside run function
private Timer myTimer;
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 1000);
Try using below code. It uses a while loop which will keep of looping for-ever until two condition are met
1) i becomes greater than 20
2) flag is set to false
For each iteration, it will sleep for 1 minute
public static void main(String[] args) {
int i = 0;
boolean flag = true;
try {
while (i < 20 && flag) {
TimeUnit.MINUTES.sleep(1);
// Expecting some logic to increment the value of i
// Or change the flag value of this to exit the while loop
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
Related
I'm trying to make an image twinkle with RaffleImage(); while I'm executing the timer, my character is immune to any collision, I want it to be immune only for 2 seconds, so the timer get execute only for 2 seconds and then get finished.
I've tried subtracting System.currentTimeMillis() but any variable I create from this method, have always the same value, making me get a zero from that subtracting.
Do you know how I can stop or pause the timer after any elapsed time in seconds?
immuneTimer = new Timer(50, new ActionListener() {
#Override
public synchronized void actionPerformed(ActionEvent e) {
long initMillis = System.currentTimeMillis();
if (System.currentTimeMillis() - initMillis > 2000 ) { // this substract gives me 0
initImages();
setImmune(false); // so this never reached
immuneTimer.stop();
} else {
raffleImage(); //its executing like forever;
}
}
});
The Swing timer fires a an ActionEvent. From the event you can use getSource() to get the source of the event. Cast that source to the swing timer object and use that to turn it off.
To know when to turn it off you need to have a variable count the number of times the swing timer is invoked. When the variable reaches that amount, turn it off.
int elapsedTime = 0;
int timerDelay = 50;
int max = 2000;
public void actionPerformed(ActionEvent ae) {
elapsedTime += timerDelay; // you could use getDelay here but it
// is in milliseconds.
if (elapsedTime >= max) {
Timer s = (Timer)ae.getSource();
s.stop();
}
// rest of code
}
How to be limit number of times call and runs method OnScrolled() in RecyclerView ?? Because there are a number of conditions in it, very much executing this code,Cause slowdown the application.
condition :
if (dy < 0 && mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() >= 10 && !mStateScrollTop) {
YoYo.with(Techniques.SlideInUp)
.duration(150)
.playOn(iv_go_to_top);
mStateScrollTop = true;
} else if (dy > 0 && mStateScrollTop) {
YoYo.with(Techniques.SlideOutDown)
.duration(150)
.playOn(iv_go_to_top);
mStateScrollTop = false;
}
I would do something like this:
onScrolled() {
synchronized(this) {
if(!ready)
return;
else
ready = false;
}
// your current onScroll body
}
And then you would launch a thread setting a ready variable to true in regular intervals. Something like this:
private void launchOnScrollThread() {
new Thread() {
#Override
public void run() {
// endless loop - maybe you would like to put some condition to end the loop
for(;;) {
ready = true;
Thread.sleep(100); // wait here for 100 milliseconds
}
}
}.start();
}
This would ensure that your current code in onScroll will be executed at most every 100 milliseconds, which should speed it up. Sorry that it's kind of a pseudocode, hope it makes sense to you and will be helpful.
I have the follow problem:
i'm writing an chat bot in java and i want to call a method even x minutes.
So i read an "Timer.Schedule" is what i need. So i write the following method:
public function timerMethod()
{
int time = 10;
...
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 1000 * 60 * time // 1MSec * 1Sec * xMin
);
}
At the beginning the loop works fine but after a few hours (i think it's after 10-15 hours) the loop dont work anymore...
I dont know why i dont work and dont get any error message :(
Can someone help me pleace???
So you want code to run for x minutes, correct?
If so, convert the time you want the code to run for into milliseconds like this : 1 minute = 60000 ms. There is a method called System.currentTimeMillis(), this will return a value of miliseconds from the EPOCH date (Jan 1, 1970).
You can use a while loop like this:
`
int msTime = 60000; //1 Minute = 60000 MS
int doUntil = ms + System.currentTimeMillis(); //1 minute
while(System.currentTimeMillis() != doUntil)
{
//Code here
System.out.println(¨Hello World¨); //This will print Ḧello World for 60000ms
}
Mmm well first you can stop instantiating multiple times the java.util.Timer() variable. You only need one as an attribute of the class. The timerTask is the only one there that should be reinstantiated.
private Timer timer = new Timer();
Now, surround your code inside the run function with try/catch:
public void run() {
try {
timerMethod();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
Are you calling that timerMethod just once? You can add to this code some prints too in order to check whenever you reschedule your function and when you run your method.
I have a thread that runs while a condition is false. For each second it is false, then it will add 1 second to the time, then return that time. My problem is that at the end of the code, it returns no output, that is, no integer variable is returned to output.
Note: For this program, assume that the user correctly guesses the number, and win is true.
Edit: Code execute() has been added to the while win = false
Thread thread = new Thread() {
public int run(boolean win){
int time = 0;
while(win == false) {
try {
time++;
Thread.sleep(1000);
}
catch(Exception e) {
}
}
return time;
}
};
public void execute() {
thread.start();
}
This thread continues to increase while win is false, then returns the value of time when win is true.
public void userGuessNumber() {
boolean win = false
[...] // Options Menu Code - timer should not increment for this section
while(win == false) {
execute();
if(guess == number) {
win = true;
}
[...] // Do some code
}
}
Win is true when user guesses a number correctly. That is when the thread should stop incrementing. Then below is when the method outputs the time:
public void outputInfo() {
System.out.print("The time it had taken to guess the number: ");
execute();
}
Edited Code: I have added execute() in the while loop; my logic is that I want the thread to begin counting only when the user starts guessing a number. The execute() statement in the outputInfo method, I intend to print the number generated from time when the thread was running, but I believe this could be semantically incorrect.
execute is a method that runs the thread code, but for some reason the output it empty, and returns nothing.
Instead, I want it to return the number of the time that has elapsed before win reached true.
This really isn't the proper use of a thread. Multithreading should be used for event handling or having long background processes such as a download.
You can easily just track the time by using System.currentTimeMillis(), assigning it to a variable and you'll be able to get the difference of time in milliseconds. If you want it in seconds, just divide by 1000.
Here's a snippet:
public void userGuessNumber() {
boolean win = false
[...] // Options Menu Code - timer should not increment for this section
long guessNumberStarted = System.currentTimeMillis();
int timeElapsed = 0;
while (!win) {
if (guess == number) {
win = true;
timeElapsed = (int)(System.currentTimeMillis() - guessNumberStarted) / 1000;
}
}
[...] // Do some code
}
Not only is the code shortened, you don't have any unneeded code running in the background, and you can calculate the amount of time that passed with more accuracy, given that you make the variable a double or a long.
I'm looking for some help with a problem I've been having lately. I want to decrement from 200 down to 0, but I don't want it to be instant, but rather I want it to decrement over the course of a second. For example, at 0.5 seconds it would be at 100, 0.75 it would be a 50 and so on. If this is at all possible, I would love to hear from you guys!
-Thanks so much, Brandon
To do what you want, here's the answer:
int index = 200;
while(index != 0)
{
index--;
System.out.println("The value is: " + index);
try {
//200 * 5 milliseconds = 1 second
Thread.sleep((long) 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
You might want to put this in a thread. Here's a page that could help you:
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
You can try with a timer. Schedule it to run at the required interval and decrement the value as desired. There are other options as well like iterating in a loop, waiting for the required interval and then decrementing.
you can involve a Java Thread,in run method make a loop and use Thread.sleep method under condition.
you can use some thing like this. find the proportion you want to delay and delay it in each iteration using thread.sleep.
in each iteration the running thread(main program) will sleep for 200 mili seconds
public static void main(String[] args) throws InterruptedException {
for(int i = 0;i<200;i++){
Date date = new Date();
Thread.sleep(200); // this is mili seconds
System.out.println(date.getTime());
}
}