计时器无法执行任务

时间:2017-07-24 11:40:23

标签: java timer scheduled-tasks timertask periodic-task

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

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

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

示例:

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

最简单的方法是使用Java TimeUnit

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

也可能是由于在守护进程模式下启动Timer引起的。如果所有main方法都设置了定时器然后返回定时器将永远不会执行,因为它是最后剩下的线程,并且因为它是守护程序线程,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