JuggernautDad
JuggernautDad

Reputation: 1145

Problem with Java Timer

I am having a weird problem with timers... My Timer works correctly when testing in NetBeans, but as soon as I compile and run directly from the terminal (Ubuntu 10.4), the task that is supposed to occur every minute executes once and never executes again...

Here is my code:

public static void main(String[] args) throws SQLException
{
    // schedule db update task to occur every 15 mins
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask ()
        {
            @Override public void run()
            {
                doUpdate();
            }
        } , 0, updateInterval * 1000 * 60 );
        System.out.print("Starting auto update @ ");

    // schedule cpu usage check to occur every 1 min
    Timer cpu = new Timer();
    cpu.scheduleAtFixedRate(new TimerTask ()
        {
            @Override public void run()
            {
                getCPU();
            }
        } , 0, cpuUpdateInterval * 1000 * 60 );
}

Is there something that I am doing wrong?

Upvotes: 1

Views: 2167

Answers (2)

trashgod
trashgod

Reputation: 205765

With this code,

import java.util.Timer;
import java.util.TimerTask;

/** @see http://stackoverflow.com/questions/4503829 */
public class TimerTest {

    private static final int MAX = 8;

    public static void main(String[] args) {
        final Timer cpu = new Timer();
        cpu.scheduleAtFixedRate(new TimerTask() {

            private int count;

            @Override
            public void run() {
                count++;
                System.out.println("Count: " + count);
                if (count == MAX) {
                    cpu.cancel();
                }
            }
        }, 100, 1000);
    }
}

I got the expected results:

$ make run
java -version
java version "1.6.0_20"
OpenJDK Runtime Environment (IcedTea6 1.9.2) (6b20-1.9.2-0ubuntu1~10.04.1)
OpenJDK Client VM (build 19.0-b09, mixed mode, sharing)
java TimerTest
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 6
Count: 7
Count: 8

Upvotes: 1

brian_d
brian_d

Reputation: 11360

What does getCPU() do? If it is running JNA/JNI code or an external library, maybe you are missing the library from your command line settings.

Upvotes: 2

Related Questions