定时器无法执行任务

Timer not able to execute task

我正在尝试定期执行任务。例如:

class MyTimerTask implements TimerTask 
{
   public void run() {
     // Some actions to perform
   }
   Timer cleaner = new Timer(true);
   cleaner.scheduleAtFixedRate(new MyTimerTask(), 0, PURGE_INTERVAL);
}

但是,运行 方法只执行一次。但是,如果我将第一次时间延迟设置为 10 秒,那么 run 方法甚至不会执行一次。

示例:

cleaner.scheduleAtFixedRate(new MyTimerTask(), 10, PURGE_INTERVAL);

我很难弄清楚你的问题到底是什么,所以这可能不是你想要的,但这个解决方案可能适合你:

public class MyTimerTask implements Runnable {
    private static final TimeUnit timeUnit = TimeUnit.SECONDS;
    private final ScheduledExecutorService scheduler;
    private final int period = 10;
    public static void main(String[] args) {
        new MyTimerTask();
    }
    public MyTimerTask() {
        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(this, period, period, timeUnit);
    }
    @Override
    public void run() {
        // This will run every 10 seconds
        System.out.println("Ran...");
    }
}

对我来说,这听起来像是时间单位的问题。确保您正确转换为毫秒。

最简单的方法是使用 Java 的 TimeUnit

Timer cleaner = new Timer(true);
cleaner.scheduleAtFixedRate(new MyTimerTask(),
    TimeUnit.SECONDS.toMillis(10),
    TimeUnit.SECONDS.toMillis(30));

也可能是 Timer 以守护进程模式启动引起的。如果您的所有主要方法都设置了计时器,然后 return 计时器将永远不会执行,因为它是最后一个剩余的线程,并且因为它是守护线程,JVM 将退出。

要解决此问题,要么使计时器线程不是守护进程(即在构造函数中传递 false),要么使主线程在退出前等待用户输入。

下面是一个使用以上两者的例子:

public class TimerDemo extends TimerTask {

    public void run() {
        System.out.printf("Time is now %s%n", LocalTime.now());
    }

    public static void main(String[] args) throws IOException {
        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(new TimerDemo(),
                TimeUnit.SECONDS.toMillis(5),
                TimeUnit.SECONDS.toMillis(10));
        System.out.printf("Program started at %s%n", LocalTime.now());
        System.out.println("Press enter to exit");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            // Wait for user to press enter
            reader.readLine();
        }
        System.out.println("Bye!");
    }
}

而 运行 它的输出:

Program started at 14:49:42.207
Press enter to exit
Time is now 14:49:46.800
Time is now 14:49:56.799
Time is now 14:50:06.799
Time is now 14:50:16.799
Time is now 14:50:26.799
[I pressed 'enter']
Bye!

Process finished with exit code 0