每 30 秒执行一次 Java 类的最简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2476337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:22:23  来源:igfitidea点击:

What is the simplest way to execute a Java class every 30 seconds?

javaspringjbossspring-mvcquartz-scheduler

提问by Gandalf StormCrow

I've been reading about java/spring/hibernate and worked trough a "dummy" examples so I told my friend to recommend something a bit harder for me, and now I'm stuck.. here is the simplest class I could think of

我一直在阅读有关 java/spring/hibernate 的文章,并研究了一个“虚拟”示例,所以我告诉我的朋友为我推荐一些更难的东西,现在我被卡住了..这是我能想到的最简单的类

package spring.com.practice;

public class Pitcher {

    private String shout;

    public String getShout() {
        return shout;
    }

    public void setShout(String shout) {
        this.shout = shout;
    }

    public void voice()
    {
        System.out.println(getShout());
    }

}

What is the most simple way to print out something by calling metod voice()from spring beans, and do it repeadatly every 30 seconds lets say, here is what I've got so far :

通过voice()从 spring beans 中调用 metod 打印出一些东西的最简单的方法是什么,并且每 30 秒重复一次,可以说,这是我到目前为止所得到的:

<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
    <property name="jobDetail" ref="jobSchedulerDetail" />
    <property name="startDelay" value="0" />
    <property name="repeatInterval" value="30" />
</bean>


<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="schedulerName" value="pitcherScheduler" />
    <property name="triggers">
        <list>
            <ref bean="simpleTrigger" />
        </list>
    </property>
</bean>
 <bean id="pitcher" class="spring.com.practice.Pitcher">
 <property name="shout" value="I started executing..."></property>
 </bean>

And yes I'm trying to run this on Jboss 5, I'm building a project with maven.

是的,我正在尝试在 Jboss 5 上运行它,我正在用 maven 构建一个项目。

I got some suggestions and my application context now looks like :

我得到了一些建议,我的应用程序上下文现在看起来像:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:sched="http://www.springinaction.com/schema/sched"
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springinaction.com/schema/sched
       http://www.springinaction.com/schema/sched-1.0.xsd"
       default-lazy-init="true">

   <bean id="stuffDoer" class="spring.com.practice">
   <property name="shout" value="I'm executing"/>
   </bean>

  <sched:timer-job
       target-bean="stuffDoer"
       target-method="voice"
       interval="5000" 
       start-delay="1000"
       repeat-count="10" />

</beans>

Here is my web.xml :

这是我的 web.xml :

<web-app id="simple-webapp" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>spring app</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/conf/applicationContext.xml
</param-value>
    </context-param>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.properties</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.util.Log4jConfigListener
</listener-class>
    </listener>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
</listener-class>
    </listener>
</web-app>

Now I get this exeption :

现在我得到了这个例外:

12:35:51,657 ERROR [01-SNAPSHOT]] Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I didn't realize executing something like hello world every 30 sec would be this complicated

我没有意识到每 30 秒执行一次像 hello world 这样的事情会这么复杂

回答by skaffman

I wouldn't bother with Quartz, it's overkill for something this simple. Java5 comes with its own scheduler, and it's good enough.

我不会理会 Quartz,对于这么简单的事情来说,这太过分了。Java5自带调度器,已经够用了。

Pre-Spring 3, this is was the easiest approach:

Pre-Spring 3,这是最简单的方法:

<bean class="org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean">
    <property name="scheduledExecutorTasks">
        <list>
            <bean class="org.springframework.scheduling.concurrent.ScheduledExecutorTask">
                <property name="period" value="30000"/>
                <property name="runnable">
                    <bean class="org.springframework.scheduling.support.MethodInvokingRunnable">
                        <property name="targetObject" ref="pitcher"/>
                        <property name="targetMethod" value="voice"/>
                    </bean>
                </property>
            </bean>
        </list>
    </property>
</bean>

With Spring 3, it can be ridiculously easy:

使用 Spring 3,它可以非常简单:

@Scheduled(fixedRate=30000)
public void voice() {
    System.out.println(getShout());
}

and

<beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:task="http://www.springframework.org/schema/task"
           xsi:schemaLocation="
                http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
           "> 

  <bean id="pitcher" class="spring.com.practice.Pitcher">
     <property name="shout" value="I started executing..."></property>
  </bean>

  <task:annotation-driven/>

</beans>

回答by sundary

With Spring 3, you can quickly use @Scheduledand @Async!

使用 Spring 3,您可以快速使用@Scheduled@Async

Check this out: Implement @Scheduled in Spring Application

看看这个:在 Spring 应用程序中实现 @Scheduled

回答by Reverend Gonzo

It looks complicated, but that really is the best way to do that. You can configure it external to the application, and let spring/quartz handle execution.

看起来很复杂,但这确实是做到这一点的最佳方式。您可以在应用程序外部对其进行配置,并让 spring/quartz 处理执行。

This is especially useful when the method you need to call is a transaction-enabled service call.

当您需要调用的方法是启用事务的服务调用时,这尤其有用。

回答by Wiretap

I have something similar but using the QuartzConnector class in mule, which runs every 20 seconds. See example. The other way would be to use the cron type time entry see Quartz Cron

我有类似的东西,但在 mule 中使用 QuartzConnector 类,它每 20 秒运行一次。参见示例。另一种方法是使用 cron 类型时间条目,请参阅Quartz Cron

    <endpoint name="poller" address="quartz://poller1" type="sender" connector="QuartzConnector">
      <properties>
        <property name="repeatInterval" value="20000"/>
        <property name="payloadClassName" value="org.jdom.Document" />
        <property name="startDelay" value="10000"/>                
      </properties>
    </endpoint>  

回答by Basheer AL-MOMANI

you can use scheduled task

您可以使用计划任务

<bean id="EmptyScopesRemover" class="com.atypon.pagebuilder.core.tasks.impl.EmptyScopesRemoverImpl"/>

<task:scheduled-tasks>
    <task:scheduled ref="EmptyScopesRemover" method="remove" cron="0 */1 * * * *"/>
</task:scheduled-tasks>

here is a video https://www.youtube.com/watch?v=mt5R_KBlhTU

这是一个视频https://www.youtube.com/watch?v=mt5R_KBlhTU

and you can check this answer to corn values https://stackoverflow.com/a/32521238/4251431

你可以检查这个关于玉米价值的答案 https://stackoverflow.com/a/32521238/4251431