Ali Hashemi
Ali Hashemi

Reputation: 3408

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!?

Upvotes: 0

Views: 6388

Answers (2)

RNJ
RNJ

Reputation: 15572

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

Upvotes: 8

Jorge Córdoba
Jorge Córdoba

Reputation: 52133

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.

Upvotes: 8

Related Questions