view flys-artifacts/src/main/java/de/intevation/flys/wsplgen/Scheduler.java @ 3807:d73c43798a99 pre2.6-2011-11-04

merged flys-backend/pre2.6-2011-11-04
author Thomas Arendsen Hein <thomas@intevation.de>
date Fri, 28 Sep 2012 12:14:51 +0200
parents 6b9877a9f6c1
children 368040e5c400
line wrap: on
line source
package de.intevation.flys.wsplgen;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import de.intevation.flys.artifacts.model.WSPLGENJob;


public class Scheduler implements Runnable {

    public static final int MAX_WSPLGEN_PROCESSES = 1;


    protected List<WSPLGENJob> jobs;


    private static Scheduler INSTANCE;

    private static final Logger logger = Logger.getLogger(Scheduler.class);



    private Scheduler() {
        jobs = Collections.synchronizedList(new LinkedList<WSPLGENJob>());
    }


    public static Scheduler getInstance() {
        if (INSTANCE == null) {
            logger.info("Create new WSPLGEN Scheduler...");

            INSTANCE = new Scheduler();
            new Thread(INSTANCE).start();
        }

        return INSTANCE;
    }


    public void addJob(WSPLGENJob job) {
        synchronized(jobs) {
            jobs.add(job);

            logger.info("New WSPLGEN job added.");

            jobs.notifyAll();
        }
    }


    public WSPLGENJob getJob() {
        synchronized(jobs) {
            if (!jobs.isEmpty()) {
                return jobs.remove(0);
            }

            return null;
        }
    }


    public void run() {
        logger.info("WSPLGEN Scheduler started.");

        for (;;) {
            try {
                doRun();
            }
            catch (InterruptedException ie) {
                logger.warn("Interrupt in WSPLGEN Scheduler -> restart it!");
            }
        }
    }


    public void doRun()
    throws InterruptedException
    {
        for (;;) {
            final WSPLGENJob job = getJob();

            if (job != null) {
                logger.debug("Got new job to execute...");

                Thread t = new Thread() {
                    public void run() {
                        JobExecutor executor = new JobExecutor(job);
                        executor.execute();
                    }
                };

                t.start();
                t.join();
            }
            else {
                logger.info("No more jobs in Scheduler -> go sleep!");
                synchronized (jobs) {
                    jobs.wait();
                }

                logger.info("New jobs in Scheduler -> wake up!");
            }
        }
    }
}
// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8 :

http://dive4elements.wald.intevation.org