简体   繁体   中英

Java Timer.Schedule (infiniti loop) stop running

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM