停止OSGI包中的计时器

时间:2015-03-05 19:57:30

标签: java timer osgi osgi-bundle

所以,我有一个OSGi包,可以创建一个像这样的计时器......

       Timer timer = new Timer(true);
       // running timer task as daemon thread
       timer.scheduleAtFixedRate(this, 0, 2 * 1000);//my class extends the timer task 
       // cancel after 60s
        try 
        {
           Thread.sleep(60000);
        } 
        catch (InterruptedException e) 
        {
           e.printStackTrace();
        } 
        finally 
        {
           timer.cancel();
        }

只要在计时器任务结束之前没有停止OSGi包,这就可以正常工作。如果我试图在定时器超时之前停止捆绑(即60秒),我得到一个例外,即捆绑不能干净地停止。

在我的捆绑的取消激活方法中,我取消了计时器,但我想因为线程正在休眠,捆绑的停止在超时之前没有被调用

我只是想了解是否有一种方法可以在超时之前停止捆绑,这也会杀死计时器任务?

1 个答案:

答案 0 :(得分:3)

您可以使用interrupts取消线程。在并发性方面,OSGi与其他应用程序没有什么不同。

您发布的代码应该在自己独立的线程中运行,您需要保留对该线程的引用。当bundle被停用时,使用Thread.interrupt()向该线程发送一个中断。你的代码实际上已经工作了,但可能不想打印堆栈跟踪。这是一个例子:

cancelTimerThread = new Thread() {
    public void run() {
        try {
            Thread.sleep(60000);
        } 
        catch (InterruptedException e) {
            log.debug("timer canceled by bundle stop");
        }
        timer.cancel();
    }
}
cancelTimerThread.start();

关于捆绑停用:

public void stop() {
    // signal thread to cancel timer early
    cancelTimerThread.interrupt();
}

请注意,使用timer.cancel()时,当前正在运行的计时器任务将不会中止。如果它是一个长时间运行的任务,你也应该向该任务发送一个中断。

相关问题