java - 自动定时器@Schedule Java EE

标签 java jakarta-ee timer

我是 Java EE 的新用户,我正在开发一个必须定期更新天气的应用程序。 我使用注释创建了一个自动计时器,以便每 5 分钟更新一次。我想动态地更改时间(管理员可以更改它):

@Schedule(minute="*/5",hour = "*", persistent = false)
public void weatherUpdate(){
}

我需要一个名为 frequency 的整型变量,其中包含天气更新的频率。我试图做这样的事情,但这没有用:

int freq=5;

@Schedule(minute="*/freq",hour = "*", persistent = false)
public void weatherUpdate(){
}

你知道什么解决办法吗?

最佳答案

一个可能的解决方案是使用 TimerService ,例如,您可以创建编程计时器。

例如

@Singleton 
@Startup 
public class ProgrammaticTimer { 

    @Resource 
    TimerService timerService; 

    public void createTimer(String timerId, int frec){ 
        ScheduleExpression expression = new ScheduleExpression(); 
        expression.minute("*/"+freq).hour("*"); 
        timerService.createCalendarTimer(expression, new TimerConfig(timerId, true)); 
    } 

    @Timeout 
    public void execute(){ 
        System.out.println("----Invoked: " + System.currentTimeMillis()); 
    } 
}

要编辑定时器的频率,首先您需要取消当前定时器并使用新值创建新定时器。

例如

@Singleton 
@Startup 
public class ProgrammaticTimer { 

    @Resource 
    TimerService timerService; 

    public void createTimer(String timerId, int freq){ 
        ScheduleExpression expression = new ScheduleExpression(); 
        expression.minute("*/"+freq).hour("*"); 
        timerService.createCalendarTimer(expression, new TimerConfig(timerId, true)); 
    } 

    public void editTimer(String timerId, int freq){ 
        cancelTimer(timerId)
        ScheduleExpression expression = new ScheduleExpression(); 
        expression.minute("*/"+freq).hour("*"); 
        timerService.createCalendarTimer(expression, new TimerConfig(timerId, true)); 
    } 

    public void cancelTimer(String timerId) {
        if (timerService.getTimers() != null) {
            for (Timer timer : timerService.getTimers()) {
                if (timer.getInfo().equals(timerId)) {
                    timer.cancel();
                }
            }
        }
    }

    @Timeout 
    public void execute(){ 
        System.out.println("----Invoked: " + System.currentTimeMillis()); 
    } 
}

另请参阅:Using the Timer Service

希望对您有所帮助。

关于java - 自动定时器@Schedule Java EE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27824420/

相关文章:

java - 复制(通过 Web API)完成;不管怎样,我的 pipe 坏了。怎么解决呢?

javascript - 如何替换目标数组字符串并将其更改为用户输入字符串

java - 延迟提交 cloudlet 任务

java - JPA 2/Hibernate - 更新复杂实体的最佳方法?

java - 我可以在 JavaEE 8 中注入(inject) 2 个同名的接口(interface)吗?

c - linux中时序计算的引用是什么

java - UPI交易ID是如何生成的

Java - Eclipse - 如何强制应用程序仅运行一个主程序?

当循环位于timer1_Tick函数内部时C#错误

java - 事件派发线程与逻辑线程分离,防止UI阻塞