有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Maven/Vaadin项目的服务器后台运行java类?

问题: 我需要每24小时运行一个java函数。它从一个站点获取一些数据,并将这些数据推送到数据库。我不知道如何创建计时器,它将在Tom Cat服务器上成功运行。我有maven/Vaadin项目。所以现在我想知道如何启动定时器功能,将运行在服务器上,而不是在现场

白色石英:

arhucture

计时器:

public class TimerData implements org.quartz.Job {


    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();


    public TimerData() throws SchedulerException, InterruptedException {
        sched.scheduleJob(job, trigger);
        sched.start();
        Thread.sleep(90L * 1000L);
        sched.shutdown(true);
    }
    // define the job and tie it to our HelloJob class
    JobDetail job = newJob(TimerData.class)
            .withIdentity("job1", "group1")
            .build();
    // compute a time that is on the next round minute
    Date runTime = evenMinuteDate(new Date());

    // Trigger the job to run on the next round minute
    Trigger trigger = newTrigger()
            .withIdentity("trigger1", "group1")
            .startAt(runTime)
            .build();

    // Tell quartz to schedule the job using our trigger


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // Say Hello to the World and display the date/time
        System.out.println("Hello World! - " + new Date());

        try {
            FillData.povni();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

依赖关系:

 <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>2.2.1</version>
  </dependency>
  <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz-jobs</artifactId>
        <version>2.2.1</version>
  </dependency>

Contlistener:

public class ContListener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener {
    private ServletContext context = null;
    // Public constructor is required by servlet spec
    public ContListener() {
    }

    // -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------
    public void contextInitialized(ServletContextEvent sce) {
      /* This method is called when the servlet context is
         initialized(when the Web application is deployed). 
         You can initialize servlet context related data here.
      */
        context = sce.getServletContext();
    }

    public void contextDestroyed(ServletContextEvent sce) {
      /* This method is invoked when the Servlet Context 
         (the Web application) is undeployed or 
         Application Server shuts down.
      */
    }

    // -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
    public void sessionCreated(HttpSessionEvent se) {
      /* Session is created. */
    }

    public void sessionDestroyed(HttpSessionEvent se) {
      /* Session is destroyed. */
    }

    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------

    public void attributeAdded(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute 
         is added to a session.
      */
    }

    public void attributeRemoved(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is removed from a session.
      */
    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attibute
         is replaced in a session.
      */
    }
}

网络。xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>quartz:config-file</param-name>
        <param-value>quartz.properties</param-value>
    </context-param>

    <context-param>
        <param-name>quartz:shutdown-on-unload</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>quartz:wait-on-shutdown</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>quartz:start-on-load</param-name>
        <param-value>true</param-value>
    </context-param>

    <listener>
        <listener-class>org.quartz.ee.servlet.QuartzInitializerListener</listener-class>
    </listener>
    <listener>
        <listener-class>ContListener</listener-class>
    </listener>
</web-app>

共 (1) 个答案

  1. # 1 楼答案

    为此创建了一个虚拟样板项目。 看看https://github.com/dhruvpsaru/quartz-test

    我使用了我认为更好的注释来代替xml

    波姆。xml是

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>web-app</groupId>
      <artifactId>app</artifactId>
      <packaging>war</packaging>
      <version>1.0</version>
      <name>app Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
    
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.0.1</version>
        </dependency>
    
        <dependency>
          <groupId>org.quartz-scheduler</groupId>
          <artifactId>quartz</artifactId>
          <version>2.2.1</version>
        </dependency>
    
        <dependency>
          <groupId>org.quartz-scheduler</groupId>
          <artifactId>quartz-jobs</artifactId>
          <version>2.2.1</version>
        </dependency>
    
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.21</version>
        </dependency>
        <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <version>1.1.7</version>
        </dependency>
    
      </dependencies>
      <build>
        <finalName>app</finalName>
      </build>
    </project>
    

    创建一个servlet作为

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    
        import javax.servlet.http.HttpServletResponse;
        import java.io.IOException;
        import java.io.PrintWriter;
    
    
        @WebServlet(
                name = "AnnotatedServlet",
                description = "A sample annotated servlet",
                urlPatterns = {"/test"}
        )
        public class AppServlet extends HttpServlet {
    
            private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
                logger.info("            in servlet         -");
    
                PrintWriter writer = resp.getWriter();
                writer.println("<html>Hello, I am a Java servlet!</html>");
                writer.flush();
            }
        }
    

    创建一个工作类作为

    package quartz;
    
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class SimpleJob implements Job {
    
        private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            logger.info("This is my first quartz job!!");
        }
    }
    

    并创建一个监听器作为

    import org.quartz.*;
    import org.quartz.impl.StdSchedulerFactory;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    
    import static org.quartz.TriggerBuilder.newTrigger;
    
    @WebListener
    public class QuartzScheduler implements ServletContextListener {
    
        private Scheduler scheduler = null;
        private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            logger.info("Context Initialized");
    
            try {
                // Setup the Job class and the Job group
                JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity(
                        "CronQuartzJob", "Group").build();
    
                // Create a Trigger that fires every 5 minutes.
                Trigger trigger = newTrigger()
                        .withIdentity("TriggerName", "Group")
                        .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                        .build();
    
                // Setup the Job and Trigger with Scheduler & schedule jobs
                scheduler = new StdSchedulerFactory().getScheduler();
                scheduler.start();
                scheduler.scheduleJob(job, trigger);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
            logger.info("Context Destroyed");
            try
            {
                scheduler.shutdown();
            }
            catch (SchedulerException e)
            {
                e.printStackTrace();
            }
        }
    }
    

    现在去做mvn clean package并部署target/app.war