use of org.quartz.Scheduler in project openhab1-addons by openhab.
the class DropboxSynchronizer method schedule.
/**
* Schedules either a job handling the Upload (<code>LOCAL_TO_DROPBOX</code>)
* or Download (<code>DROPBOX_TO_LOCAL</code>) direction depending on
* <code>isUpload</code>.
*
* @param interval the Trigger interval as cron expression
* @param isUpload
*/
private void schedule(String interval, boolean isUpload) {
String direction = isUpload ? "Upload" : "Download";
try {
Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
JobDetail job = newJob(SynchronizationJob.class).withIdentity(direction, DROPBOX_SCHEDULER_GROUP).build();
CronTrigger trigger = newTrigger().withIdentity(direction, DROPBOX_SCHEDULER_GROUP).withSchedule(CronScheduleBuilder.cronSchedule(interval)).build();
logger.debug("Scheduled synchronization job (direction={}) with cron expression '{}'", direction, interval);
sched.scheduleJob(job, trigger);
} catch (SchedulerException e) {
logger.warn("Could not create synchronization job: {}", e.getMessage());
}
}
use of org.quartz.Scheduler in project openhab1-addons by openhab.
the class DropboxSynchronizer 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(DROPBOX_SCHEDULER_GROUP));
if (jobKeys.size() > 0) {
sched.deleteJobs(new ArrayList<JobKey>(jobKeys));
logger.debug("Found {} synchronization jobs to delete from DefaultScheduler (keys={})", jobKeys.size(), jobKeys);
}
} catch (SchedulerException e) {
logger.warn("Couldn't remove synchronization job: {}", e.getMessage());
}
}
use of org.quartz.Scheduler in project openhab1-addons by openhab.
the class OceanicBinding method execute.
@Override
protected void execute() {
if (isProperlyConfigured()) {
Scheduler sched = null;
try {
sched = StdSchedulerFactory.getDefaultScheduler();
} catch (SchedulerException e) {
logger.error("An exception occurred while getting a reference to the Quartz Scheduler");
}
// reset the contextMap before rebuilding it
for (String serialPort : serialDevices.keySet()) {
Set<String> itemNames = contextMap.get(serialPort);
if (itemNames != null) {
contextMap.clear();
}
}
for (OceanicBindingProvider provider : providers) {
for (String itemName : provider.getItemNames()) {
String serialPort = provider.getSerialPort(itemName);
SerialDevice serialDevice = serialDevices.get(serialPort);
boolean serialDeviceReady = true;
if (serialDevice == null) {
serialDevice = new SerialDevice(serialPort);
try {
serialDevice.initialize();
} catch (InitializationException e) {
logger.error("Could not open serial port " + serialPort + ": " + e.getMessage());
serialDeviceReady = false;
} catch (Throwable e) {
logger.error("Could not open serial port " + serialPort + ": " + e.getMessage());
serialDeviceReady = false;
}
if (serialDeviceReady) {
serialDevice.setEventPublisher(eventPublisher);
serialDevices.put(serialPort, serialDevice);
}
}
Set<String> itemNames = contextMap.get(serialPort);
if (itemNames == null) {
itemNames = new HashSet<String>();
contextMap.put(serialPort, itemNames);
}
itemNames.add(itemName);
if (serialDeviceReady) {
// set up the polling jobs
boolean jobExists = false;
// enumerate each job group
try {
for (String group : sched.getJobGroupNames()) {
// enumerate each job in group
if (group.equals("Oceanic-" + provider.toString())) {
for (JobKey jobKey : sched.getJobKeys(jobGroupEquals(group))) {
if (jobKey.getName().equals(itemName + "-" + provider.getValueSelector(itemName).toString())) {
jobExists = true;
break;
}
}
}
}
} catch (SchedulerException e1) {
logger.error("An exception occurred while querying the Quartz Scheduler ({})", e1.getMessage());
}
if (!jobExists && OceanicValueSelector.getValueSelector(provider.getValueSelector(itemName), ValueSelectorType.GET) != null) {
// set up the Quartz jobs
JobDataMap map = new JobDataMap();
map.put("SerialPort", serialPort);
map.put("ValueSelector", OceanicValueSelector.getValueSelector(provider.getValueSelector(itemName), ValueSelectorType.GET));
map.put("Binding", this);
JobDetail job = newJob(OceanicBinding.PollJob.class).withIdentity(itemName + "-" + provider.getValueSelector(itemName).toString(), "Oceanic-" + provider.toString()).usingJobData(map).build();
Trigger trigger = newTrigger().withIdentity(itemName + "-" + provider.getValueSelector(itemName).toString(), "Oceanic-" + provider.toString()).startNow().withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(provider.getPollingInterval(itemName))).build();
try {
logger.debug("Adding a poll job {} for {}", job.getKey(), itemName);
sched.scheduleJob(job, trigger);
} catch (SchedulerException e) {
logger.error("An exception occurred while scheduling a Quartz Job");
}
}
// kill the Quartz jobs that we do not need anymore
try {
for (String group : sched.getJobGroupNames()) {
// enumerate each job in group
if (group.equals("Oceanic-" + provider.toString())) {
for (JobKey jobKey : sched.getJobKeys(jobGroupEquals(group))) {
if (findFirstMatchingBindingProvider(jobKey.getName().split("-")[0]) == null) {
logger.debug("Removing a poll job {} for {}", jobKey, itemName);
sched.deleteJob(jobKey);
}
}
}
}
} catch (SchedulerException e1) {
logger.error("An exception occurred while querying the Quartz Scheduler ({})", e1.getMessage());
}
}
}
}
// close down the serial ports that do not have any Items anymore associated to them
for (String serialPort : serialDevices.keySet()) {
SerialDevice serialDevice = serialDevices.get(serialPort);
Set<String> itemNames = contextMap.get(serialPort);
if (itemNames == null || itemNames.size() == 0) {
contextMap.remove(serialPort);
logger.debug("Closing the serial port {}", serialPort);
serialDevice.close();
serialDevices.remove(serialPort);
}
}
}
}
use of org.quartz.Scheduler in project spring-framework by spring-projects.
the class SchedulerFactoryBean method createScheduler.
/**
* Create the Scheduler instance for the given factory and scheduler name.
* Called by {@link #afterPropertiesSet}.
* <p>The default implementation invokes SchedulerFactory's {@code getScheduler}
* method. Can be overridden for custom Scheduler creation.
* @param schedulerFactory the factory to create the Scheduler with
* @param schedulerName the name of the scheduler to create
* @return the Scheduler instance
* @throws SchedulerException if thrown by Quartz methods
* @see #afterPropertiesSet
* @see org.quartz.SchedulerFactory#getScheduler
*/
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) throws SchedulerException {
// Override thread context ClassLoader to work around naive Quartz ClassLoadHelper loading.
Thread currentThread = Thread.currentThread();
ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
boolean overrideClassLoader = (this.resourceLoader != null && !this.resourceLoader.getClassLoader().equals(threadContextClassLoader));
if (overrideClassLoader) {
currentThread.setContextClassLoader(this.resourceLoader.getClassLoader());
}
try {
SchedulerRepository repository = SchedulerRepository.getInstance();
synchronized (repository) {
Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);
Scheduler newScheduler = schedulerFactory.getScheduler();
if (newScheduler == existingScheduler) {
throw new IllegalStateException("Active Scheduler of name '" + schedulerName + "' already registered " + "in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!");
}
if (!this.exposeSchedulerInRepository) {
// Need to remove it in this case, since Quartz shares the Scheduler instance by default!
SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName());
}
return newScheduler;
}
} finally {
if (overrideClassLoader) {
// Reset original thread context ClassLoader.
currentThread.setContextClassLoader(threadContextClassLoader);
}
}
}
use of org.quartz.Scheduler in project spring-framework by spring-projects.
the class QuartzSupportTests method schedulerFactoryBeanWithApplicationContext.
@Test
public void schedulerFactoryBeanWithApplicationContext() throws Exception {
TestBean tb = new TestBean("tb", 99);
StaticApplicationContext ac = new StaticApplicationContext();
final Scheduler scheduler = mock(Scheduler.class);
SchedulerContext schedulerContext = new SchedulerContext();
given(scheduler.getContext()).willReturn(schedulerContext);
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) {
return scheduler;
}
};
schedulerFactoryBean.setJobFactory(null);
Map<String, Object> schedulerContextMap = new HashMap<>();
schedulerContextMap.put("testBean", tb);
schedulerFactoryBean.setSchedulerContextAsMap(schedulerContextMap);
schedulerFactoryBean.setApplicationContext(ac);
schedulerFactoryBean.setApplicationContextSchedulerContextKey("appCtx");
try {
schedulerFactoryBean.afterPropertiesSet();
schedulerFactoryBean.start();
Scheduler returnedScheduler = schedulerFactoryBean.getObject();
assertEquals(tb, returnedScheduler.getContext().get("testBean"));
assertEquals(ac, returnedScheduler.getContext().get("appCtx"));
} finally {
schedulerFactoryBean.destroy();
}
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
Aggregations