简体   繁体   中英

Thread.sleep() doesn't work continously

I have a program to read some RSS feeds, parse them, and copy the links somewhere else. Well! I want to check the RSS feeds about every 10 minutes for probable updates. I wrote this piece of code:

   @Override
public void run() {
    while (true) {
        // check feeds here
        try {
            Thread.sleep(600000);
        } catch (InterruptedException ex) {
            // exception handing
        }
    }
}

When I run it, for a day or two, it's OK and running. But usually after 3 or 4 days, it goes to sleep and never wakes up again!!! So it doesn't update the RSS feeds.

How can I solve this issue!?

If I have to guess I would say there's probably a bug in the code that reads the feeds which raises an unhandled exception which in turn ends the thread. To you it seems like the thread never wakes, when in fact it dies.

public void run() {
    while (true) {
        // check feeds here   <<<---- Look for the bug here
        try {
            Thread.sleep(600000);
        } catch (InterruptedException ex) {
            // exception handing
        }
    }
}

It's very unlikely that there's a bug in the Thread.sleep method (as it is widely use almost everywhere). Anyway, debug and check to see if your thread is still alive or if it has died.

Try the java executor libraries. They were introduced in java 5 and make this sort of code more efficient and cleaner.

ScheduledExecutorService es = Executors.newScheduledThreadPool(1);
es.schedule(new Runnable(){
    @Override
    public void run() {
        //RSS checking
    }
}, 10, TimeUnit.MINUTES);

There is a lot going on in these libraries so it is worth checking them out.

Perhaps it is stopping because of memory or something like this. Try the method above to check every 10 minutes.

There is also the concept of Callable (instead of Runnable) which allows throwing exceptions which may help you debug this. You get a future object returned which you can use to help. This link looks quite good http://www.javacodegeeks.com/2011/09/java-concurrency-tutorial-callable.html

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