Search in sources :

Example 11 with Scheduler

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

the class MapDBPersistenceService method cancelAllJobs.

/**
     * Delete all quartz scheduler jobs of the group <code>Dropbox</code>.
     */
private void cancelAllJobs() {
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        Set<JobKey> jobKeys = sched.getJobKeys(jobGroupEquals(SCHEDULER_GROUP));
        if (jobKeys.size() > 0) {
            sched.deleteJobs(new ArrayList<JobKey>(jobKeys));
            logger.debug("Found {} MapDB-Jobs to delete from DefaultScheduler (keys={})", jobKeys.size(), jobKeys);
        }
    } catch (SchedulerException e) {
        logger.warn("Couldn't remove Commit-Job: {}", e.getMessage());
    }
}
Also used : JobKey(org.quartz.JobKey) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler)

Example 12 with Scheduler

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

the class Db4oPersistenceService method scheduleJob.

/**
     * Schedules new quartz scheduler jobs for committing transactions and
     * backing up the database
     */
private void scheduleJob() {
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        // schedule commit-job
        JobDetail job = newJob(CommitJob.class).withIdentity("Commit_Transaction", SCHEDULER_GROUP).build();
        SimpleTrigger trigger = newTrigger().withIdentity("Commit_Transaction", SCHEDULER_GROUP).withSchedule(repeatSecondlyForever(commitInterval)).build();
        sched.scheduleJob(job, trigger);
        logger.debug("Scheduled Commit-Job with interval {}sec.", commitInterval);
        // schedule backup-job
        JobDetail backupJob = newJob(BackupJob.class).withIdentity("Backup_DB", SCHEDULER_GROUP).build();
        CronTrigger backupTrigger = newTrigger().withIdentity("Backup_DB", SCHEDULER_GROUP).withSchedule(CronScheduleBuilder.cronSchedule(backupInterval)).build();
        sched.scheduleJob(backupJob, backupTrigger);
        logger.debug("Scheduled Backup-Job with cron expression '{}'", backupInterval);
    } catch (SchedulerException e) {
        logger.warn("Could not create Job: {}", e.getMessage());
    }
}
Also used : JobDetail(org.quartz.JobDetail) CronTrigger(org.quartz.CronTrigger) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler) SimpleTrigger(org.quartz.SimpleTrigger)

Example 13 with Scheduler

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

the class Db4oPersistenceService method cancelAllJobs.

/**
     * Delete all quartz scheduler jobs of the group <code>Dropbox</code>.
     */
private void cancelAllJobs() {
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        Set<JobKey> jobKeys = sched.getJobKeys(jobGroupEquals(SCHEDULER_GROUP));
        if (jobKeys.size() > 0) {
            sched.deleteJobs(new ArrayList<JobKey>(jobKeys));
            logger.debug("Found {} DB4O-Jobs to delete from DefaultScheduler (keys={})", jobKeys.size(), jobKeys);
        }
    } catch (SchedulerException e) {
        logger.warn("Couldn't remove Commit-Job: {}", e.getMessage());
    }
}
Also used : JobKey(org.quartz.JobKey) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler)

Example 14 with Scheduler

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

the class PlugwiseBinding method scheduleJobs.

private void scheduleJobs(Scheduler scheduler) {
    for (PlugwiseBindingProvider provider : providers) {
        for (PlugwiseBindingConfigElement element : provider.getIntervalList()) {
            PlugwiseCommandType type = element.getCommandType();
            if (type.getJobClass() == null) {
                continue;
            }
            if (stick.getDevice(element.getId()) == null) {
                logger.debug("The Plugwise device with id {} is not yet defined", element.getId());
                // check if the config string really contains a MAC address
                Pattern MAC_PATTERN = Pattern.compile("(\\w{16})");
                Matcher matcher = MAC_PATTERN.matcher(element.getId());
                if (matcher.matches()) {
                    List<CirclePlus> cps = stick.getDevicesByClass(CirclePlus.class);
                    if (!cps.isEmpty()) {
                        CirclePlus cp = cps.get(0);
                        if (!cp.getMAC().equals(element.getId())) {
                            // a circleplus has been added/detected and it is not what is in the binding config
                            PlugwiseDevice device = new Circle(element.getId(), stick, element.getId());
                            stick.addDevice(device);
                            logger.debug("Plugwise added Circle with MAC address: {}", element.getId());
                        }
                    } else {
                        logger.warn("Plugwise can not guess the device that should be added. Consider defining it in the openHAB configuration file");
                    }
                } else {
                    logger.warn("Plugwise can not add a valid device without a proper MAC address. {} can not be used", element.getId());
                }
            }
            if (stick.getDevice(element.getId()) != null) {
                String jobName = element.getId() + "-" + type.getJobClass().toString();
                if (!isExistingJob(scheduler, jobName)) {
                    // set up the Quartz jobs
                    JobDataMap map = new JobDataMap();
                    map.put(STICK_JOB_DATA_KEY, stick);
                    map.put(MAC_JOB_DATA_KEY, stick.getDevice(element.getId()).MAC);
                    JobDetail job = newJob(type.getJobClass()).withIdentity(jobName, "Plugwise-" + provider.toString()).usingJobData(map).build();
                    Trigger trigger = newTrigger().withIdentity(element.getId() + "-" + type.getJobClass().toString(), "Plugwise-" + provider.toString()).startNow().withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(element.getInterval())).build();
                    try {
                        scheduler.scheduleJob(job, trigger);
                    } catch (SchedulerException e) {
                        logger.error("An exception occurred while scheduling a Plugwise Quartz Job", e);
                    }
                }
            } else {
                logger.error("Error scheduling a Quartz Job for a non-defined Plugwise device (" + element.getId() + ")");
            }
        }
    }
    List<CirclePlus> cps = stick.getDevicesByClass(CirclePlus.class);
    if (!cps.isEmpty()) {
        CirclePlus cp = cps.get(0);
        String jobName = cp.MAC + "-SetCirclePlusClock";
        if (!isExistingJob(scheduler, jobName)) {
            JobDataMap map = new JobDataMap();
            map.put(CirclePlus.CIRCLE_PLUS_JOB_DATA_KEY, cp);
            JobDetail job = newJob(SetClockJob.class).withIdentity(jobName, "Plugwise").usingJobData(map).build();
            CronTrigger trigger = newTrigger().withIdentity(jobName, "Plugwise").startNow().withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?")).build();
            try {
                Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
                sched.scheduleJob(job, trigger);
            } catch (SchedulerException e) {
                logger.error("Error scheduling Circle+ setClock Quartz Job", e);
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) JobDataMap(org.quartz.JobDataMap) CronTrigger(org.quartz.CronTrigger) SchedulerException(org.quartz.SchedulerException) Matcher(java.util.regex.Matcher) PlugwiseCommandType(org.openhab.binding.plugwise.PlugwiseCommandType) Scheduler(org.quartz.Scheduler) PlugwiseBindingConfigElement(org.openhab.binding.plugwise.internal.PlugwiseGenericBindingProvider.PlugwiseBindingConfigElement) SetClockJob(org.openhab.binding.plugwise.internal.CirclePlus.SetClockJob) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) CronTrigger(org.quartz.CronTrigger) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) PlugwiseBindingProvider(org.openhab.binding.plugwise.PlugwiseBindingProvider)

Example 15 with Scheduler

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

the class EventReloaderJob method execute.

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    final String config = context.getJobDetail().getJobDataMap().getString(KEY_CONFIG);
    CalendarRuntime eventRuntime = EventStorage.getInstance().getEventCache().get(config);
    log.debug("running EventReloaderJob for config : {}", config);
    // reload cached events (if necessary)
    if (!cachedEventsLoaded.containsKey(config)) {
        try {
            log.debug("reload cached events for config: {}", eventRuntime.getConfig().getKey());
            for (File fileCalendarKeys : new File(CalDavLoaderImpl.CACHE_PATH).listFiles()) {
                if (!eventRuntime.getConfig().getKey().equals(Util.getFilename(fileCalendarKeys.getName()))) {
                    log.trace("not our config : {}", Util.getFilename(fileCalendarKeys.getName()));
                    continue;
                }
                log.trace("found our config : {}", Util.getFilename(fileCalendarKeys.getName()));
                final Collection<File> icsFiles = FileUtils.listFiles(fileCalendarKeys, new String[] { "ics" }, false);
                for (File icsFile : icsFiles) {
                    try {
                        FileInputStream fis = new FileInputStream(icsFile);
                        log.debug("loading events from file : {}", icsFile);
                        loadEvents(Util.getFilename(icsFile.getAbsolutePath()), new org.joda.time.DateTime(icsFile.lastModified()), fis, eventRuntime.getConfig(), new ArrayList<String>(), true);
                    } catch (IOException e) {
                        log.error("cannot load events for file: " + icsFile, e);
                    } catch (ParserException e) {
                        log.error("cannot load events for file: " + icsFile, e);
                    }
                }
                break;
            }
        } catch (Throwable e) {
            log.error("cannot load events", e);
        } finally {
            cachedEventsLoaded.put(config, true);
        }
    }
    try {
        log.debug("loading events for config: " + config);
        List<String> oldEventIds = new ArrayList<String>();
        for (EventContainer eventContainer : eventRuntime.getEventMap().values()) {
            oldEventIds.add(eventContainer.getFilename());
            log.debug("old eventcontainer -- id : {} -- filename : {} -- calcuntil : {} -- lastchanged : {} -- ishistoric : {}", eventContainer.getEventId(), eventContainer.getFilename(), eventContainer.getCalculatedUntil(), eventContainer.getLastChanged(), eventContainer.isHistoricEvent());
            if (log.isDebugEnabled()) {
                for (int i = 0; i < eventContainer.getEventList().size(); i++) {
                    CalDavEvent elem = eventContainer.getEventList().get(i);
                    log.debug("old eventlist contient l'evenement : {} -- deb : {} -- fin : {} -- lastchang {}", elem.getName(), elem.getStart(), elem.getEnd(), elem.getLastChanged());
                }
            }
        }
        loadEvents(eventRuntime, oldEventIds);
        // stop all events in oldMap
        removeDeletedEvents(config, oldEventIds);
        for (EventNotifier notifier : CalDavLoaderImpl.instance.getEventListenerList()) {
            try {
                notifier.calendarReloaded(config);
            } catch (Exception e) {
                log.error("error while invoking listener", e);
            }
        }
        // print All scheduled jobs :
        if (log.isDebugEnabled()) {
            log.debug("jobs scheduled : ");
            Scheduler scheduler = CalDavLoaderImpl.instance.getScheduler();
            for (String groupName : CalDavLoaderImpl.instance.getScheduler().getJobGroupNames()) {
                for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
                    String jobName = jobKey.getName();
                    String jobGroup = jobKey.getGroup();
                    // get job's trigger
                    List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
                    Date nextFireTime = triggers.get(0).getNextFireTime();
                    log.debug("[job] : {} - [groupName] : {} - {}", jobName, jobGroup, nextFireTime);
                }
            }
        }
    } catch (SardineException e) {
        log.error("error while loading calendar entries: {} ({} - {} )", e.getMessage(), e.getStatusCode(), e.getResponsePhrase(), e);
        throw new JobExecutionException("error while loading calendar entries", e, false);
    } catch (Exception e) {
        log.error("error while loading calendar entries: {}", e.getMessage(), e);
        throw new JobExecutionException("error while loading calendar entries", e, false);
    }
}
Also used : Scheduler(org.quartz.Scheduler) ArrayList(java.util.ArrayList) JobKey(org.quartz.JobKey) SardineException(com.github.sardine.impl.SardineException) Trigger(org.quartz.Trigger) JobExecutionException(org.quartz.JobExecutionException) EventNotifier(org.openhab.io.caldav.EventNotifier) PropertyList(net.fortuna.ical4j.model.PropertyList) List(java.util.List) ArrayList(java.util.ArrayList) ComponentList(net.fortuna.ical4j.model.ComponentList) PeriodList(net.fortuna.ical4j.model.PeriodList) ParserException(net.fortuna.ical4j.data.ParserException) EventContainer(org.openhab.io.caldav.internal.EventStorage.EventContainer) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ParserException(net.fortuna.ical4j.data.ParserException) JobExecutionException(org.quartz.JobExecutionException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException) SardineException(com.github.sardine.impl.SardineException) Date(java.util.Date) CalDavEvent(org.openhab.io.caldav.CalDavEvent) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime) File(java.io.File)

Aggregations

Scheduler (org.quartz.Scheduler)73 SchedulerException (org.quartz.SchedulerException)37 JobDetail (org.quartz.JobDetail)33 Trigger (org.quartz.Trigger)22 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)8 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