如何在Java中使用计时器在特定时间内运行作业?

use*_*373 0 java multithreading timer jsf-2

我正在开发一个Web应用程序,我需要运行一个60秒的线程,需要检查来自Web服务的响应.如果响应在60秒内到达,我将转发成功,然后我将在60秒后转发到超时页面.我在使用JSF 2.0?我曾想过使用Timer,但不确定我是否只能在sprcefic的时间内运行定时器.

这有什么聪明的解决方案?

Sim*_*Sez 6

是的,您可以创建一个在一定时间后过期的计时器.请参阅此链接http://docs.oracle.com/javaee/1.4/api/javax/ejb/TimerService.html.

Java <vers.6

  1. 创建Session-或MessageDriven-Bean
  2. 注入TimerService

    @Ressource
    TimerService ts;
    
    Run Code Online (Sandbox Code Playgroud)
  3. 创建计时器

    ...
    // create Timer which starts after 10s every 10s
    Timer timer = ts.createTimer(10000, 10000, "Test-Timer");
    ...
    
    Run Code Online (Sandbox Code Playgroud)

    重要事项:Timer Interval必须> 7sec,请参阅Java规范

  4. 创建定时器触发时要执行的方法

    @Timeout //marks Method to be executed by Timer
    public void timerFired(Timer timer) {
      // your code here
    }
    
    Run Code Online (Sandbox Code Playgroud)

Java> vers.6

@Schedule-Annotation 非常满意

    @Schedule(second="*/45", minute="*", hour="*", persistent="false")
    public void scheduler() {
      // your code here
    }
Run Code Online (Sandbox Code Playgroud)

上面的代码实现了一个计时器,它每小时每隔45分钟被触发一次.有关cron语法的更多信息,请查看维基百科.

这两种方法都实现了Serializable-Interface,因此它们都是线程安全的.

如果你想扩展这个基本功能,你应该看一下Quartz.

希望这有帮助!玩得开心!