Java Timer.Schedule (infiniti loop) stop running - java

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.

Related

How can I stop a Swing Timer after n seconds?

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
}

Run an if-statement for a certain amount of time

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

Pause Stopwatch Timer with Sleep Thread?

I'm trying to make a stopwatch in Java and don't know how to pause and continue my timer. Here is what I have done so far.
startButton.addActionListener(this);
stopButton.addActionListener(this);
pauseButton.addActionListener(this);
public void actionPerformed(ActionEvent e) {
Calendar aCalendar = Calendar.getInstance();
if (e.getSource() == startButton){
start = aCalendar.getTimeInMillis();
startButton.setBackground(Color.GREEN);
stopButton.setBackground(null);
pauseButton.setBackground(null);
} else if (e.getSource() == stopButton) {
stopButton.setBackground(Color.RED);
startButton.setBackground(null);
pauseButton.setBackground(null);
aJLabel.setText("Elapsed time is: " +
(double) (aCalendar.getTimeInMillis() - start) / 1000 );
} else if (e.getSource() == pauseButton) {
pauseButton.setBackground(Color.YELLOW);
stopButton.setBackground(null);
startButton.setBackground(null);
}
}
As you can see, I've only changed the colors for my pause button. I don't really know how to pause the thread by having the user click on the button. All examples I've found of thread.sleep() were with a specific time.
You can use the swing.Timer (not util.Timer) like this:
int interval = 100; // set milliseconds for each loop
Timer timer = new Timer(interval, (evt) -> repeatingProccess());
// create the method repeatingProccess() with your
// code that makes the clock tick
startButton.addActionListener(e -> timer.start());
stopButton.addActionListener( e -> {
timer.stop();
// here refresh your clock with some code...
};
pauseButton.addActionListener(e -> timer.stop());
You write a method called repeatingProccess() and it works in its own thread again and again every interval milliseconds. For a clock that counts seconds you can do this:
int interval = 1000;
int seconds = 0;
public void repeatingProccess() {
seconds++ ;
}
note:
The second will not be exactly 1000 milliseconds but around 1001 because of the time needed to run seconds++ but you can fix that as well by getting System time before and after and substracting the difference from your clock. You should use the Calendar API for this.

Extend time of an Countdowntimer

Why is this Code not working ?
This code should extend the Countdowntimer to 10 sec (everytime when point is 20 , 40 , 60) etc.But when I start it and my score is by 20 it shows in a TextView a right value of time.But then it is gone in 1 sec and the Countdowntimer got the old value and continue.Someone a idea ?
int bonus_time = 1 , sec = 10000 , point == 0;
points_timer =new CountDownTimer(sec,1000) {
#Override
public void onTick(long millisUntilFinished)
{
if ( point == (bonus_time * 20))
{
++bonus_time;
millisUntilFinished += 10000;
sec += 10000;
}
++point;
}
#Override
public void onFinish()
{
bonus_time = 1;
}
};
When you create a timer with the sec variable for its time, it does not magically connect the two so when the value of sec changes the timer's time changes, it just uses the value of sec once when you make the timer.
Same goes for changing millisUntilFinished, it's a parameter you got from a callback, by changing its value you are not doing anything.
The only way to change a timer's time is to create a new one. This is my suggestion:
// GLOBAL VARIABLES
CountDownTimer points_timer;
int bonus_time = 1 , sec = 10000 , point == 0;
public void createTimer()
{
points_timer =new CountDownTimer(sec,1000) {
#Override
public void onTick(long millisUntilFinished)
{
sec = millisUntilFinished;
if ( point == (bonus_time * 20))
{
++bonus_time;
//millisUntilFinished += 10000;
sec += 10000;
createTimer();
}
++point;
}
#Override
public void onFinish()
{
bonus_time = 1;
}
};
}
The creation of the timer is surrounded by a function, and that function is called each time the bonus is gained to recreate the timer with the new value of sec.
You should also call that method once in place of your previous code, to initially create the timer.
Hope this works..
There is no way to extend a CountDownTimer, no method in the class provides this.
Your attempt to add time to sec is useless, I even wonder how it can compile. Anyway, in Java integers are passed by value, so once you passed 1000, you passed it and can't change that value.
The only alernative is to re-create a new timer and use it instead of the old one. Or recode everything, a timer of your own that you can extend.
in
public void onTick(long millisUntilFinished)
you do
millisUntilFinished += 10000;
you can not assign to primitive parameter and expect that it changes anything outside of that method (eg. scope of millisUntilFinished is onTick method and nothing more)

Java decrement over time

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

Categories