Search in sources :

Example 56 with Trigger

use of org.quartz.Trigger in project Dempsy by Dempsy.

the class OutputQuartzHelper method getSimpleTrigger.

/**
 * Gets the simple trigger.
 *
 * @param timeUnit the time unit
 * @param timeInterval the time interval
 * @return the simple trigger
 */
public Trigger getSimpleTrigger(TimeUnit timeUnit, int timeInterval) {
    SimpleScheduleBuilder simpleScheduleBuilder = null;
    simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
    switch(timeUnit) {
        case MILLISECONDS:
            simpleScheduleBuilder.withIntervalInMilliseconds(timeInterval).repeatForever();
            break;
        case SECONDS:
            simpleScheduleBuilder.withIntervalInSeconds(timeInterval).repeatForever();
            break;
        case MINUTES:
            simpleScheduleBuilder.withIntervalInMinutes(timeInterval).repeatForever();
            break;
        case HOURS:
            simpleScheduleBuilder.withIntervalInHours(timeInterval).repeatForever();
            break;
        case DAYS:
            simpleScheduleBuilder.withIntervalInHours(timeInterval * 24).repeatForever();
            break;
        default:
            // default 1 sec
            simpleScheduleBuilder.withIntervalInSeconds(1).repeatForever();
    }
    Trigger simpleTrigger = TriggerBuilder.newTrigger().withSchedule(simpleScheduleBuilder).build();
    return simpleTrigger;
}
Also used : Trigger(org.quartz.Trigger) SimpleScheduleBuilder(org.quartz.SimpleScheduleBuilder)

Example 57 with Trigger

use of org.quartz.Trigger 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 58 with Trigger

use of org.quartz.Trigger in project OpenClinica by OpenClinica.

the class ViewJobServlet method processRequest.

@Override
protected void processRequest() throws Exception {
    // TODO single stage servlet where we get the list of jobs
    // and push them out to the JSP page
    // related classes will be required to generate the table rows
    // and eventually links to view and edit the jobs as well
    FormProcessor fp = new FormProcessor(request);
    // First we must get a reference to a scheduler
    scheduler = getScheduler();
    XsltTriggerService xsltTriggerSrvc = new XsltTriggerService();
    // Scheduler sched = sfb.getScheduler();
    Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(xsltTriggerSrvc.getTriggerGroupNameForExportJobs()));
    String[] triggerNames = triggerKeys.stream().toArray(String[]::new);
    //      String[]    triggerNames          =           scheduler.getJobNames(XsltTriggerService.TRIGGER_GROUP_NAME);
    // logger.info("trigger list: "+triggerNames.length);
    // logger.info("trigger names: "+triggerNames.toString());
    ArrayList triggerBeans = new ArrayList();
    for (String triggerName : triggerNames) {
        Trigger trigger = scheduler.getTrigger(TriggerKey.triggerKey(triggerName, xsltTriggerSrvc.getTriggerGroupNameForExportJobs()));
        try {
            logger.debug("prev fire time " + trigger.getPreviousFireTime().toString());
            logger.debug("next fire time " + trigger.getNextFireTime().toString());
            logger.debug("final fire time: " + trigger.getFinalFireTime().toString());
        } catch (NullPointerException npe) {
        // could be nulls in the dates, etc
        }
        // logger.info(trigger.getDescription());
        // logger.info("");//getJobDataMap()
        TriggerBean triggerBean = new TriggerBean();
        triggerBean.setFullName(trigger.getKey().getName());
        triggerBean.setPreviousDate(trigger.getPreviousFireTime());
        triggerBean.setNextDate(trigger.getNextFireTime());
        if (trigger.getDescription() != null) {
            triggerBean.setDescription(trigger.getDescription());
        }
        // setting: frequency, dataset name
        JobDataMap dataMap = new JobDataMap();
        DatasetDAO datasetDAO = new DatasetDAO(sm.getDataSource());
        StudyDAO studyDao = new StudyDAO(sm.getDataSource());
        if (trigger.getJobDataMap().size() > 0) {
            dataMap = trigger.getJobDataMap();
            int dsId = dataMap.getInt(ExampleSpringJob.DATASET_ID);
            String periodToRun = dataMap.getString(ExampleSpringJob.PERIOD);
            triggerBean.setPeriodToRun(periodToRun);
            DatasetBean dataset = (DatasetBean) datasetDAO.findByPK(dsId);
            triggerBean.setDataset(dataset);
            triggerBean.setDatasetName(dataset.getName());
            StudyBean study = (StudyBean) studyDao.findByPK(dataset.getStudyId());
            triggerBean.setStudyName(study.getName());
        // triggerBean.setStudyName(dataMap.getString(ExampleSpringJob.STUDY_NAME));
        }
        logger.debug("Trigger Priority: " + trigger.getKey().getName() + " " + trigger.getPriority());
        if (scheduler.getTriggerState(TriggerKey.triggerKey(triggerName, XsltTriggerService.TRIGGER_GROUP_NAME)) == Trigger.TriggerState.PAUSED) {
            triggerBean.setActive(false);
            logger.debug("setting active to false for trigger: " + trigger.getKey().getName());
        } else {
            triggerBean.setActive(true);
            logger.debug("setting active to TRUE for trigger: " + trigger.getKey().getName());
        }
        triggerBeans.add(triggerBean);
    // our wrapper to show triggers
    }
    ArrayList allRows = TriggerRow.generateRowsFromBeans(triggerBeans);
    EntityBeanTable table = fp.getEntityBeanTable();
    String[] columns = { resword.getString("name"), resword.getString("previous_fire_time"), resword.getString("next_fire_time"), resword.getString("description"), resword.getString("period_to_run"), resword.getString("dataset"), resword.getString("study"), resword.getString("actions") };
    table.setColumns(new ArrayList(Arrays.asList(columns)));
    table.hideColumnLink(3);
    table.hideColumnLink(7);
    table.setQuery("ViewJob", new HashMap());
    // table.addLink("", "CreateUserAccount");
    table.setSortingColumnInd(0);
    table.setRows(allRows);
    table.computeDisplay();
    request.setAttribute("table", table);
    // throw new NullPointerException("faking an error here");
    forwardPage(Page.VIEW_JOB);
}
Also used : TriggerBean(org.akaza.openclinica.bean.admin.TriggerBean) JobDataMap(org.quartz.JobDataMap) HashMap(java.util.HashMap) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) EntityBeanTable(org.akaza.openclinica.web.bean.EntityBeanTable) DatasetBean(org.akaza.openclinica.bean.extract.DatasetBean) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) ArrayList(java.util.ArrayList) DatasetDAO(org.akaza.openclinica.dao.extract.DatasetDAO) TriggerKey(org.quartz.TriggerKey) Trigger(org.quartz.Trigger) XsltTriggerService(org.akaza.openclinica.service.extract.XsltTriggerService) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO)

Example 59 with Trigger

use of org.quartz.Trigger in project OpenClinica by OpenClinica.

the class ViewSingleJobServlet method processRequest.

@Override
protected void processRequest() throws Exception {
    FormProcessor fp = new FormProcessor(request);
    // changes to this servlet, we now look at group name too, tbh 05/2009
    String triggerName = fp.getString("tname");
    String gName = fp.getString("gname");
    String groupName = "";
    if (gName.equals("") || gName.equals("0")) {
        groupName = XsltTriggerService.TRIGGER_GROUP_NAME;
    } else {
        // if (gName.equals("1")) {
        groupName = TRIGGER_IMPORT_GROUP;
    }
    // << tbh 09/03/2009 #4143
    scheduler = getScheduler();
    Trigger trigger = scheduler.getTrigger(new TriggerKey(triggerName, groupName));
    if (trigger == null) {
        groupName = XsltTriggerService.TRIGGER_GROUP_NAME;
        trigger = scheduler.getTrigger(new TriggerKey(triggerName.trim(), groupName));
    }
    // << tbh 09/03/2009 #4143
    // above is a hack, if we add more trigger groups this will have
    // to be redone
    logger.debug("found trigger name: " + triggerName);
    logger.debug("found group name: " + groupName);
    TriggerBean triggerBean = new TriggerBean();
    JobDataMap dataMap = new JobDataMap();
    AuditEventDAO auditEventDAO = new AuditEventDAO(sm.getDataSource());
    try {
        triggerBean.setFullName(trigger.getKey().getName());
        triggerBean.setPreviousDate(trigger.getPreviousFireTime());
        triggerBean.setNextDate(trigger.getNextFireTime());
        // >> set active here, tbh 10/08/2009
        if (scheduler.getTriggerState(new TriggerKey(triggerName, groupName)) == Trigger.TriggerState.PAUSED) {
            triggerBean.setActive(false);
            logger.debug("setting active to false for trigger: " + trigger.getKey().getName());
        } else {
            triggerBean.setActive(true);
            logger.debug("setting active to TRUE for trigger: " + trigger.getKey().getName());
        }
        // <<
        if (trigger.getDescription() != null) {
            triggerBean.setDescription(trigger.getDescription());
        }
        if (trigger.getJobDataMap().size() > 0) {
            dataMap = trigger.getJobDataMap();
            String contactEmail = dataMap.getString(XsltTriggerService.EMAIL);
            logger.debug("found email: " + contactEmail);
            // int dsId = new Integer(datasetId).intValue();
            if (gName.equals("") || gName.equals("0")) {
                String exportFormat = dataMap.getString(XsltTriggerService.EXPORT_FORMAT);
                String periodToRun = dataMap.getString(ExampleSpringJob.PERIOD);
                // int userId = new Integer(userAcctId).intValue();
                int dsId = dataMap.getInt(ExampleSpringJob.DATASET_ID);
                triggerBean.setExportFormat(exportFormat);
                triggerBean.setPeriodToRun(periodToRun);
                DatasetDAO datasetDAO = new DatasetDAO(sm.getDataSource());
                DatasetBean dataset = (DatasetBean) datasetDAO.findByPK(dsId);
                triggerBean.setDataset(dataset);
            }
            int userId = dataMap.getInt(ExampleSpringJob.USER_ID);
            // need to set information, extract bean, user account bean
            UserAccountDAO userAccountDAO = new UserAccountDAO(sm.getDataSource());
            triggerBean.setContactEmail(contactEmail);
            UserAccountBean userAccount = (UserAccountBean) userAccountDAO.findByPK(userId);
            triggerBean.setUserAccount(userAccount);
            ArrayList<AuditEventBean> triggerLogs = auditEventDAO.findAllByAuditTable(trigger.getKey().getName());
            // set the table for the audit event beans here
            ArrayList allRows = AuditEventRow.generateRowsFromBeans(triggerLogs);
            EntityBeanTable table = fp.getEntityBeanTable();
            String[] columns = { resword.getString("date_and_time"), resword.getString("action_message"), resword.getString("entity_operation"), // resword.getString("study_subject_ID"),
            resword.getString("changes_and_additions"), resword.getString("actions") };
            table.setColumns(new ArrayList(Arrays.asList(columns)));
            table.setAscendingSort(false);
            table.hideColumnLink(1);
            table.hideColumnLink(3);
            table.hideColumnLink(4);
            table.setQuery("ViewSingleJob?tname=" + triggerName + "&gname=" + gName, new HashMap());
            table.setRows(allRows);
            table.computeDisplay();
            request.setAttribute("table", table);
        }
    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        logger.debug(" found NPE " + e.getMessage());
        e.printStackTrace();
    }
    // need to show the extract for which this runs, which files, etc
    // in other words the job data map
    request.setAttribute("triggerBean", triggerBean);
    request.setAttribute("groupName", groupName);
    forwardPage(Page.VIEW_SINGLE_JOB);
}
Also used : TriggerBean(org.akaza.openclinica.bean.admin.TriggerBean) JobDataMap(org.quartz.JobDataMap) HashMap(java.util.HashMap) FormProcessor(org.akaza.openclinica.control.form.FormProcessor) EntityBeanTable(org.akaza.openclinica.web.bean.EntityBeanTable) DatasetBean(org.akaza.openclinica.bean.extract.DatasetBean) ArrayList(java.util.ArrayList) AuditEventDAO(org.akaza.openclinica.dao.admin.AuditEventDAO) DatasetDAO(org.akaza.openclinica.dao.extract.DatasetDAO) UserAccountDAO(org.akaza.openclinica.dao.login.UserAccountDAO) TriggerKey(org.quartz.TriggerKey) Trigger(org.quartz.Trigger) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) AuditEventBean(org.akaza.openclinica.bean.admin.AuditEventBean)

Example 60 with Trigger

use of org.quartz.Trigger 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

Trigger (org.quartz.Trigger)104 JobDetail (org.quartz.JobDetail)51 SchedulerException (org.quartz.SchedulerException)40 CronTrigger (org.quartz.CronTrigger)29 Test (org.junit.Test)23 Scheduler (org.quartz.Scheduler)22 JobDataMap (org.quartz.JobDataMap)21 SimpleTrigger (org.quartz.SimpleTrigger)20 TriggerKey (org.quartz.TriggerKey)20 TriggerBuilder.newTrigger (org.quartz.TriggerBuilder.newTrigger)19 JobKey (org.quartz.JobKey)16 ArrayList (java.util.ArrayList)13 Date (java.util.Date)12 List (java.util.List)5 Command (org.openhab.core.types.Command)5 InetSocketAddress (java.net.InetSocketAddress)4 SocketChannel (java.nio.channels.SocketChannel)4 ParseException (java.text.ParseException)4 FormProcessor (org.akaza.openclinica.control.form.FormProcessor)4 ProtoTrigger (co.cask.cdap.proto.ProtoTrigger)3