Example usage for java.util.concurrent ScheduledExecutorService submit

List of usage examples for java.util.concurrent ScheduledExecutorService submit

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledExecutorService submit.

Prototype

<T> Future<T> submit(Runnable task, T result);

Source Link

Document

Submits a Runnable task for execution and returns a Future representing that task.

Usage

From source file:com.ilscipio.scipio.common.FileListener.java

/**
 *  Start a file listener (WatchService) and run a service of a given name and writes the result to the database
 *  Can be used to implements EECAs to auto-update information based on file changes
 **//*from   w ww  .j a v  a2 s. c  o  m*/
public static void startFileListener(String name, String location) {

    try {
        if (UtilValidate.isNotEmpty(name) && UtilValidate.isNotEmpty(location)) {

            if (getThreadByName(name) != null) {
                Debug.logInfo("Filelistener " + name + " already started. Skipping...", module);
            } else {
                URL resLocation = UtilURL.fromResource(location);
                Path folderLocation = Paths.get(resLocation.toURI());
                if (folderLocation == null) {
                    throw new UnsupportedOperationException("Directory not found");
                }

                final WatchService folderWatcher = folderLocation.getFileSystem().newWatchService();
                // register all subfolders
                Files.walkFileTree(folderLocation, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        dir.register(folderWatcher, StandardWatchEventKinds.ENTRY_CREATE,
                                StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
                        return FileVisitResult.CONTINUE;
                    }
                });

                // start the file watcher thread below
                ScipioWatchQueueReader fileListener = new ScipioWatchQueueReader(folderWatcher, name, location);
                ScheduledExecutorService executor = ExecutionPool.getScheduledExecutor(
                        FILE_LISTENER_THREAD_GROUP, "filelistener-startup",
                        Runtime.getRuntime().availableProcessors(), 0, true);
                try {
                    executor.submit(fileListener, name);
                } finally {
                    executor.shutdown();
                }
                Debug.logInfo("Starting FileListener thread for " + name, module);
            }
        }
    } catch (Exception e) {
        Debug.logError("Could not start FileListener " + name + " for " + location + "\n" + e, module);

    }
}