codestory

Ausführen einer Hintergrundaufgabe in der Java Servlet-Anwendung

  1. Example

1. Example

Das ist ein Beispiel zur Simulation einer regelmäßigen Aufgabe, die unter Ihrer Applikation Servlet implizit läuft. Konkret erstellt sie auf einer bestimmten Zeit eine Datei sitemap.xml, die in dem Hauptverzeichnis der Applikation web gelegt wird
SiteMapGenerator.java
package com.o7planning.example.servlet.listener;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class SiteMapGenerator implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        Runnable command = new SiteMapThread(event.getServletContext());
        // Delay 1 Minute to first execution
        long initialDelay = 1;
        TimeUnit unit = TimeUnit.MINUTES;
        // period the period between successive executions
        long period = 60;// 60 Minute!

        scheduler.scheduleAtFixedRate(command, initialDelay, period, unit);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>ServletListenerExample</display-name>



    <listener>
        <listener-class>com.o7planning.example.servlet.listener.SiteMapGenerator</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>
SiteMapThread.java
package com.o7planning.example.servlet.listener;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletContext;

public class SiteMapThread implements Runnable {

    private ServletContext context;

    public SiteMapThread(ServletContext context) {
        this.context = context;
    }

    @Override
    public void run() {
        System.out.println("Generate sitemap ... " + new Date());

        try {
            this.createFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Finish generation");
    }

    private void createFile() throws IOException {
        System.out.println("Generate file sitemap.xml to: "
                + context.getRealPath(""));
        String path = context.getRealPath("sitemap.xml");
        File file = new File(path);
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.write("<?xml version='1.0' ?>");
        writer.write("<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9' "
                + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'  "
                + " xsi:schemaLocation='http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'>");
        //
        writer.write("<url>");
        writer.write("<loc>http://o7planning.org</loc>");
        writer.write("<changefreq>daily</changefreq>");
        writer.write("<priority>0.80</priority>");
        writer.write("</url>");
        //
        writer.write("<url>");
        writer.write("<loc>http://o7planning.org/index.html</loc>");
        writer.write("<changefreq>daily</changefreq>");
        writer.write("<priority>0.80</priority>");
        writer.write("</url>");
        //
        writer.write("</urlset>");
        writer.close();
    }

}