Search in sources :

Example 36 with Scheduler

use of org.quartz.Scheduler in project searchcode-server by boyter.

the class JobService method startIndexSvnRepoJobs.

/**
     * Creates a svn repo indexer job which will pull from the list of git repositories and start
     * indexing them
     */
public void startIndexSvnRepoJobs(String uniquename) {
    try {
        Scheduler scheduler = Singleton.getScheduler();
        JobDetail job = newJob(IndexSvnRepoJob.class).withIdentity("updateindex-svn-" + uniquename).build();
        SimpleTrigger trigger = newTrigger().withIdentity("updateindex-svn-" + uniquename).withSchedule(simpleSchedule().withIntervalInSeconds(this.INDEXTIME).repeatForever()).build();
        job.getJobDataMap().put("REPOLOCATIONS", this.REPOLOCATION);
        job.getJobDataMap().put("LOWMEMORY", this.LOWMEMORY);
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    } catch (SchedulerException ex) {
        Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
    }
}
Also used : JobDetail(org.quartz.JobDetail) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler) SimpleTrigger(org.quartz.SimpleTrigger)

Example 37 with Scheduler

use of org.quartz.Scheduler in project engine by craftercms.

the class SiteContextFactory method createContext.

public SiteContext createContext(String siteName) {
    Map<String, String> macroValues = Collections.singletonMap(siteNameMacroName, siteName);
    String resolvedRootFolderPath = macroResolver.resolveMacros(rootFolderPath, macroValues);
    Context context = storeService.createContext(storeType, storeServerUrl, username, password, resolvedRootFolderPath, mergingOn, cacheOn, maxAllowedItemsInCache, ignoreHiddenFiles);
    try {
        SiteContext siteContext = new SiteContext();
        siteContext.setStoreService(storeService);
        siteContext.setSiteName(siteName);
        siteContext.setContext(context);
        siteContext.setStaticAssetsPath(staticAssetsPath);
        siteContext.setTemplatesPath(templatesPath);
        siteContext.setFreeMarkerConfig(freeMarkerConfigFactory.getObject());
        siteContext.setUrlTransformationEngine(urlTransformationEngine);
        siteContext.setOverlayCallback(overlayCallback);
        siteContext.setRestScriptsPath(restScriptsPath);
        siteContext.setControllerScriptsPath(controllerScriptsPath);
        String[] resolvedConfigPaths = new String[configPaths.length];
        for (int i = 0; i < configPaths.length; i++) {
            resolvedConfigPaths[i] = macroResolver.resolveMacros(configPaths[i], macroValues);
        }
        String[] resolvedAppContextPaths = new String[applicationContextPaths.length];
        for (int i = 0; i < applicationContextPaths.length; i++) {
            resolvedAppContextPaths[i] = macroResolver.resolveMacros(applicationContextPaths[i], macroValues);
        }
        ResourceLoader resourceLoader = new ContentStoreResourceLoader(siteContext);
        HierarchicalConfiguration<?> config = getConfig(siteContext, resolvedConfigPaths, resourceLoader);
        URLClassLoader classLoader = getClassLoader(siteContext);
        ScriptFactory scriptFactory = getScriptFactory(siteContext, classLoader);
        ConfigurableApplicationContext appContext = getApplicationContext(siteContext, classLoader, config, resolvedAppContextPaths, resourceLoader);
        siteContext.setConfigPaths(resolvedConfigPaths);
        siteContext.setApplicationContextPaths(resolvedAppContextPaths);
        siteContext.setGroovyClassesPath(groovyClassesPath);
        siteContext.setScriptFactory(scriptFactory);
        siteContext.setConfig(config);
        siteContext.setGlobalApplicationContext(globalApplicationContext);
        siteContext.setApplicationContext(appContext);
        siteContext.setClassLoader(classLoader);
        executeInitScript(siteContext, scriptFactory);
        Scheduler scheduler = scheduleJobs(siteContext);
        siteContext.setScheduler(scheduler);
        return siteContext;
    } catch (Exception e) {
        // Destroy context if the site context creation failed
        storeService.destroyContext(context);
        throw e;
    }
}
Also used : JobContext(org.craftercms.engine.util.quartz.JobContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) Context(org.craftercms.core.service.Context) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) ServletContext(javax.servlet.ServletContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) ContentStoreGroovyResourceLoader(org.craftercms.engine.util.groovy.ContentStoreGroovyResourceLoader) ResourceLoader(org.springframework.core.io.ResourceLoader) ContentStoreResourceLoader(org.craftercms.engine.util.spring.ContentStoreResourceLoader) Scheduler(org.quartz.Scheduler) ContentStoreResourceLoader(org.craftercms.engine.util.spring.ContentStoreResourceLoader) SiteContextCreationException(org.craftercms.engine.exception.SiteContextCreationException) BeansException(org.springframework.beans.BeansException) ConfigurationException(org.apache.commons.configuration2.ex.ConfigurationException) URLClassLoader(java.net.URLClassLoader) GroovyScriptFactory(org.craftercms.engine.scripting.impl.GroovyScriptFactory) ScriptFactory(org.craftercms.engine.scripting.ScriptFactory)

Example 38 with Scheduler

use of org.quartz.Scheduler in project openhab1-addons by openhab.

the class PlugwiseBinding method execute.

@Override
protected void execute() {
    if (isProperlyConfigured()) {
        try {
            Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
            scheduleJobs(sched);
        } catch (SchedulerException e) {
            logger.error("An exception occurred while getting a reference to the Quartz Scheduler ({})", e.getMessage());
        }
    }
}
Also used : SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler)

Example 39 with Scheduler

use of org.quartz.Scheduler in project openhab1-addons by openhab.

the class SonosBinding method execute.

@Override
protected void execute() {
    if (isProperlyConfigured()) {
        if (!bindingStarted) {
            // This will create necessary network resources for UPnP right away
            upnpService = new UpnpServiceImpl(new SonosUpnpServiceConfiguration(), listener);
            try {
                Iterator<SonosZonePlayer> it = sonosZonePlayerCache.iterator();
                while (it.hasNext()) {
                    SonosZonePlayer aPlayer = it.next();
                    if (aPlayer.getDevice() == null) {
                        logger.info("Querying the network for a predefined Sonos device with UDN {}", aPlayer.getUdn());
                        upnpService.getControlPoint().search(new UDNHeader(aPlayer.getUdn()));
                    }
                }
                logger.info("Querying the network for any other Sonos device");
                final UDAServiceType udaType = new UDAServiceType("AVTransport");
                upnpService.getControlPoint().search(new UDAServiceTypeHeader(udaType));
            } catch (Exception e) {
                logger.warn("An exception occurred while searching the network for Sonos devices: ", e.getMessage());
            }
            bindingStarted = true;
        }
        Scheduler sched = null;
        try {
            sched = StdSchedulerFactory.getDefaultScheduler();
        } catch (SchedulerException e) {
            logger.error("An exception occurred while getting a reference to the Quartz Scheduler");
        }
        // Cycle through the Items and setup sonos zone players if required
        for (SonosBindingProvider provider : providers) {
            for (String itemName : provider.getItemNames()) {
                for (String sonosID : provider.getSonosID(itemName)) {
                    if (!sonosZonePlayerCache.contains(sonosID)) {
                        // the device is not yet discovered on the network or not defined in the .cfg
                        // Verify that the sonosID has the format of a valid UDN
                        Pattern SONOS_UDN_PATTERN = Pattern.compile("RINCON_(\\w{17})");
                        Matcher matcher = SONOS_UDN_PATTERN.matcher(sonosID);
                        if (matcher.matches()) {
                            // Add device to the cached Configs
                            SonosZonePlayer thePlayer = new SonosZonePlayer(sonosID, self);
                            thePlayer.setUdn(new UDN(sonosID));
                            sonosZonePlayerCache.add(thePlayer);
                            // Query the network for this device
                            logger.info("Querying the network for a predefined Sonos device with UDN '{}'", thePlayer.getUdn());
                            upnpService.getControlPoint().search(new UDNHeader(thePlayer.getUdn()));
                        }
                    }
                }
            }
        }
        // Cycle through the item binding configuration that define polling criteria
        for (SonosCommandType sonosCommandType : SonosCommandType.getPolling()) {
            for (SonosBindingProvider provider : providers) {
                for (String itemName : provider.getItemNames(sonosCommandType.getSonosCommand())) {
                    for (Command aCommand : provider.getCommands(itemName, sonosCommandType.getSonosCommand())) {
                        // We are dealing with a valid device
                        SonosZonePlayer thePlayer = sonosZonePlayerCache.getById(provider.getSonosID(itemName, aCommand));
                        if (thePlayer != null) {
                            RemoteDevice theDevice = thePlayer.getDevice();
                            // Not all Sonos devices have the same capabilities
                            if (theDevice != null) {
                                if (theDevice.findService(new UDAServiceId(sonosCommandType.getService())) != null) {
                                    boolean jobExists = false;
                                    // enumerate each job group
                                    try {
                                        for (String group : sched.getJobGroupNames()) {
                                            // enumerate each job in group
                                            for (JobKey jobKey : sched.getJobKeys(jobGroupEquals(group))) {
                                                if (jobKey.getName().equals(provider.getSonosID(itemName, aCommand) + "-" + sonosCommandType.getJobClass().toString())) {
                                                    jobExists = true;
                                                    break;
                                                }
                                            }
                                        }
                                    } catch (SchedulerException e1) {
                                        logger.error("An exception occurred while quering the Quartz Scheduler ({})", e1.getMessage());
                                    }
                                    if (!jobExists) {
                                        // set up the Quartz jobs
                                        JobDataMap map = new JobDataMap();
                                        map.put("Player", thePlayer);
                                        JobDetail job = newJob(sonosCommandType.getJobClass()).withIdentity(provider.getSonosID(itemName, aCommand) + "-" + sonosCommandType.getJobClass().toString(), "Sonos-" + provider.toString()).usingJobData(map).build();
                                        Trigger trigger = newTrigger().withIdentity(provider.getSonosID(itemName, aCommand) + "-" + sonosCommandType.getJobClass().toString(), "Sonos-" + provider.toString()).startNow().withSchedule(simpleSchedule().repeatForever().withIntervalInMilliseconds(pollingPeriod)).build();
                                        try {
                                            sched.scheduleJob(job, trigger);
                                        } catch (SchedulerException e) {
                                            logger.error("An exception occurred while scheduling a Quartz Job ({})", e.getMessage());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) JobDataMap(org.quartz.JobDataMap) UpnpServiceImpl(org.teleal.cling.UpnpServiceImpl) SchedulerException(org.quartz.SchedulerException) UDNHeader(org.teleal.cling.model.message.header.UDNHeader) Matcher(java.util.regex.Matcher) Scheduler(org.quartz.Scheduler) SonosCommandType(org.openhab.binding.sonos.SonosCommandType) UDAServiceTypeHeader(org.teleal.cling.model.message.header.UDAServiceTypeHeader) ConfigurationException(org.osgi.service.cm.ConfigurationException) IllegalClassException(org.apache.commons.lang.IllegalClassException) JobExecutionException(org.quartz.JobExecutionException) SAXException(org.xml.sax.SAXException) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException) SchedulerException(org.quartz.SchedulerException) JobKey(org.quartz.JobKey) JobDetail(org.quartz.JobDetail) SonosBindingProvider(org.openhab.binding.sonos.SonosBindingProvider) Trigger(org.quartz.Trigger) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) Command(org.openhab.core.types.Command) UDAServiceType(org.teleal.cling.model.types.UDAServiceType) RemoteDevice(org.teleal.cling.model.meta.RemoteDevice) UDN(org.teleal.cling.model.types.UDN) UDAServiceId(org.teleal.cling.model.types.UDAServiceId)

Example 40 with Scheduler

use of org.quartz.Scheduler in project javaee7-samples by javaee-samples.

the class TestServlet method processRequest.

/**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Quartz Scheduler</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Quartz Scheduler</h1>");
        JobDetail simpleJob = JobBuilder.newJob(MySimpleJob.class).build();
        JobDetail cronJob = JobBuilder.newJob(MyCronJob.class).build();
        Trigger simpleTrigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever()).build();
        Trigger cronTrigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * * * ?")).build();
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        out.println("Starting the scheduler");
        scheduler.start();
        out.println("<h2>Starting Simple Trigger - every 1 second</h2>");
        scheduler.scheduleJob(simpleJob, simpleTrigger);
        out.println("<h2>Starting Cron Trigger - every 3 seconds</h2>");
        scheduler.scheduleJob(cronJob, cronTrigger);
        out.println("Sleeping for 7 seconds");
        Thread.sleep(7000);
        out.println("<br>Shutting down the scheduler");
        scheduler.shutdown();
        out.println("<br><br>Check \"server.log\" for output - 8 outputs from simple trigger, 3 from cron trigger");
        out.println("</body>");
        out.println("</html>");
    } catch (SchedulerException | InterruptedException ex) {
        Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler) PrintWriter(java.io.PrintWriter)

Aggregations

Scheduler (org.quartz.Scheduler)74 SchedulerException (org.quartz.SchedulerException)38 JobDetail (org.quartz.JobDetail)34 Trigger (org.quartz.Trigger)23 Test (org.junit.Test)19 JobKey (org.quartz.JobKey)17 SimpleTrigger (org.quartz.SimpleTrigger)16 CronTrigger (org.quartz.CronTrigger)15 JobDataMap (org.quartz.JobDataMap)10 TriggerKey (org.quartz.TriggerKey)10 TriggerBuilder.newTrigger (org.quartz.TriggerBuilder.newTrigger)9 ArrayList (java.util.ArrayList)7 Date (java.util.Date)6 Command (org.openhab.core.types.Command)5 InetSocketAddress (java.net.InetSocketAddress)4 SocketChannel (java.nio.channels.SocketChannel)4 IOException (java.io.IOException)3 RouteBuilder (org.apache.camel.builder.RouteBuilder)3 DefaultCamelContext (org.apache.camel.impl.DefaultCamelContext)3 StdSchedulerFactory (org.quartz.impl.StdSchedulerFactory)3