【问题标题】:Schedule regular task without extending TimerTask?在不扩展 TimerTask 的情况下安排常规任务?
【发布时间】:2013-04-17 06:45:02
【问题描述】:

如何在不同的线程和给定的时间间隔内重复运行此类的实例? (您已经注意到我使用的是 Java 2 EE)。

public class Gate extends AbsDBObject<Gate> implements Runnable{
  public void Run(){
    //Something
  }
}

我之前通过 Gate 类扩展 TimerTask 类并使用 Timer 来完成此操作:

Timer timer = new Timer();
Gate gates = Gate.fetchOne();
timer.schedule(gate, 0, 1000);

但在这种情况下,我不能扩展任何其他类。我该怎么办?

【问题讨论】:

    标签: java multithreading jakarta-ee timer runnable


    【解决方案1】:

    如果您使用ScheduledExecutorService,那么您只需执行Runnable 对象,而不是TimerTask 对象。

    ScheduledExecutorService executorService = 
        new ScheduledThreadPoolExecutor(corePoolSize);
    Gate gate = Gate.fetchOne();
    executorService.scheduleAtFixedRate(gate, 0, 1, TimeUnit.SECONDS);
    

    这节省了扩展的需要。

    【讨论】:

    • 你能解释一下它的用法吗?
    • 还有什么方法可以阻止它?我想添加一个开始停止链接,以便我可以控制服务
    • @dave 看看scheduleAtFixedRate方法返回的ScheduledFuture对象。
    • executorService.shutdown()
    • @dave 这是另一种选择,尽管这将取消执行器服务中的 所有 任务。另外,请注意shutdown()cancel() 选项通常不会中断正在运行的任务,除非该任务可以响应线程中断。
    【解决方案2】:

    试试

        Timer timer = new Timer();
        final Gate gates = Gate.fetchOne();
        timer.schedule(new TimerTask() {
            public void run() {
                gates.run();
            }
        }, 0, 1000);
    

    【讨论】:

    • 谢谢回复,你觉得邓肯琼斯的解决方案怎么样?
    • 它好 100%,但你问的是 TimerTask :)
    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 2012-02-18
    • 2021-07-05
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多