Java Timer的问题

时间:2010-12-21 20:56:51

标签: java timer ubuntu-10.04

我有一个奇怪的定时器问题...我的定时器在NetBeans中测试时工作正常,但是一旦我直接从终端编译和运行(Ubuntu 10.4),应该每分钟执行的任务执行一次,永远不再执行......

这是我的代码:

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

有什么我做错了吗?

2 个答案:

答案 0 :(得分:2)

getCPU()做什么?如果它正在运行JNA / JNI代码或外部库,则可能是您从命令行设置中缺少库。

答案 1 :(得分:1)

使用此代码,

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

我得到了预期的结果:

$ 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