java - 升级到 springframework.scheduling.concurrent?

标签 java spring spring-3

从 Spring 3.0 开始,ScheduledTimerTask 已被弃用,我无法理解如何升级到 org.springframework.scheduling.concurrent。

    <bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
        <property name="scheduledTimerTasks">
            <list>
                 <ref bean="onlineTimeSchedule" />
            </list>
            </property>
    </bean>

    <bean id="onlineTimeSchedule" class="org.springframework.scheduling.timer.ScheduledTimerTask">
        <property name="timerTask" class="com.example.OnlineTimerTask" />
        </property>
        <property name="period" value="60000" />
        <property name="delay" value="1000" />
    </bean>

OnlineTimerTask 扩展 java.util.TimerTask 的地方。这是一个简单的任务,每分钟向发布者发布一条消息。我检查了文档,但什么也没有。我不明白从并发包中使用哪种方式以及哪种方式最适合。

我也想把这个xml转换成Java中的@Bean。

编辑:所以我尝试用@Bean 和@Configuration 来实现xml,这就是我得到的。

@Configuration
public class ContextConfiguration {
    @Bean
    public ScheduledExecutorFactoryBean scheduledExecutorFactoryBean() {
        ScheduledExecutorFactoryBean scheduledFactoryBean = new ScheduledExecutorFactoryBean();
        scheduledFactoryBean.setScheduledExecutorTasks(new ScheduledExecutorTask[] {onlineTimeSchedule()});

        return scheduledFactoryBean;
    }

    @Bean
    public ScheduledExecutorTask onlineTimeSchedule() {
        ScheduledExecutorTask scheduledTask = new ScheduledExecutorTask();
        scheduledTask.setDelay(1000);
        scheduledTask.setPeriod(60000);
        scheduledTask.setRunnable(new OnlineTimerTask());

        return scheduledTask;
    }
}

上面的代码可以正确替换 xml 吗?在我的情况下,setScheduledExecutorTasks 会正常工作吗?我的意思是,如果 onlineTimeSchedule() 被多次调用,对同一个 bean 实例的引用会在这里工作吗?

scheduledFactoryBean.setScheduledExecutorTasks(new ScheduledExecutorTask[] {onlineTimeSchedule()});

最佳答案

使用 org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean 代替 org.springframework.scheduling.timer.TimerFactoryBean 并使用 org.springframework.scheduling。 concurrent.ScheduledExecutorTask 代替 org.springframework.scheduling.timer.ScheduledTimerTask。您需要根据需要调整属性名称和值,但这应该是不言而喻的。

或者,您可以重构您的 com.example.OnlineTimerTask 以不扩展 java.util.TimeTask,因为 ScheduledTimerTask 只需要一个 runnable。

关于java - 升级到 springframework.scheduling.concurrent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5369246/

相关文章:

java - 执行 Maven 时出错 - 不可解析的设置 settings.xml

java - 将跟踪模式设置为 cookie 以删除附加的 session ID,而不使用 web.xml

java - 如何使用 keystore 在 grpc 中使用 java 启用 ssl

spring-security - Jetty addFilter 与 Spring Security 和没有 web.xml

java - ems tibco 和发送消息的凭据

java - 混合jpa继承策略-inheritanceType.JOINED与inheritanceType.SINGLE_TABLE

java - FreeMarker Spring MVC 导入问题

google-analytics - Restkit和Google Analytics(分析)

spring - 使用自定义 Spring 安全注解

java - Elasticsearch 聚合查询没有给出预期的输出