Java Code Examples for org.quartz.Scheduler#scheduleJob()
The following examples show how to use
org.quartz.Scheduler#scheduleJob() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SchedulerTool.java From sakai with Educational Community License v2.0 | 6 votes |
/** * Convenience method for scheduling a Trigger with the Quartz Scheduler object. * @param wrapper * @throws SchedulerException */ private void scheduleTrigger(TriggerWrapper wrapper) throws SchedulerException { Trigger trigger = wrapper.getTrigger(); Scheduler scheduler = schedulerManager.getScheduler(); scheduler.scheduleJob(trigger); selectedJobDetailWrapper.getTriggerWrapperList().add(wrapper); int currentTriggerCount = selectedJobDetailWrapper.getTriggerCount() .intValue(); selectedJobDetailWrapper.setTriggerCount(Integer.valueOf( currentTriggerCount + 1)); }
Example 2
Source File: JobServiceImpl.java From griffin with Apache License 2.0 | 6 votes |
@Override public String triggerJobById(Long id) throws SchedulerException { AbstractJob job = jobRepo.findByIdAndDeleted(id, false); validateJobExist(job); Scheduler scheduler = factory.getScheduler(); JobKey jobKey = jobKey(job.getName(), job.getGroup()); if (scheduler.checkExists(jobKey)) { Trigger trigger = TriggerBuilder.newTrigger() .forJob(jobKey) .startNow() .build(); scheduler.scheduleJob(trigger); return trigger.getKey().toString(); } else { throw new GriffinException.NotFoundException(JOB_ID_DOES_NOT_EXIST); } }
Example 3
Source File: DBSyncBuilder.java From mykit-db-sync with Apache License 2.0 | 6 votes |
/** * 启动定时任务,同步数据库的数据 */ public void start() { for (int index = 0; index < jobList.size(); index++) { JobInfo jobInfo = jobList.get(index); String logTitle = "[" + code + "]" + jobInfo.getName() + " "; try { SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); JobDetail job = newJob(JobTask.class).withIdentity(MykitDbSyncConstants.JOB_PREFIX.concat(jobInfo.getName()), code).build(); job.getJobDataMap().put(MykitDbSyncConstants.SRC_DB, srcDb); job.getJobDataMap().put(MykitDbSyncConstants.DEST_DB, destDb); job.getJobDataMap().put(MykitDbSyncConstants.JOB_INFO, jobInfo); job.getJobDataMap().put(MykitDbSyncConstants.LOG_TITLE, logTitle); logger.info(jobInfo.getCron()); CronTrigger trigger = newTrigger().withIdentity(MykitDbSyncConstants.TRIGGER_PREFIX.concat(jobInfo.getName()), code).withSchedule(cronSchedule(jobInfo.getCron())).build(); sched.scheduleJob(job, trigger); sched.start(); } catch (Exception e) { e.printStackTrace(); logger.error(logTitle + e.getMessage()); logger.error(logTitle + " run failed"); continue; } } }
Example 4
Source File: DBSyncBuilder.java From Mykit with Apache License 2.0 | 6 votes |
/** * 启动定时任务,同步数据库的数据 */ public void start() { for (int index = 0; index < jobList.size(); index++) { JobInfo jobInfo = jobList.get(index); String logTitle = "[" + code + "]" + jobInfo.getName() + " "; try { SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); JobDetail job = newJob(JobTask.class).withIdentity("job-" + jobInfo.getName(), code).build(); job.getJobDataMap().put("srcDb", srcDb); job.getJobDataMap().put("destDb", destDb); job.getJobDataMap().put("jobInfo", jobInfo); job.getJobDataMap().put("logTitle", logTitle); logger.info(jobInfo.getCron()); CronTrigger trigger = newTrigger().withIdentity("trigger-" + jobInfo.getName(), code).withSchedule(cronSchedule(jobInfo.getCron())).build(); sched.scheduleJob(job, trigger); sched.start(); } catch (Exception e) { logger.info(logTitle + e.getMessage()); logger.info(logTitle + " run failed"); continue; } } }
Example 5
Source File: DefaultExceptionServiceImpl.java From rice with Educational Community License v2.0 | 6 votes |
public void scheduleExecution(Throwable throwable, PersistedMessageBO message, String description) throws Exception { KSBServiceLocator.getMessageQueueService().delete(message); PersistedMessageBO messageCopy = message.copy(); Scheduler scheduler = KSBServiceLocator.getScheduler(); JobDataMap jobData = new JobDataMap(); jobData.put(MessageServiceExecutorJob.MESSAGE_KEY, messageCopy); JobDetailImpl jobDetail = new JobDetailImpl("Exception_Message_Job " + Math.random(), "Exception Messaging", MessageServiceExecutorJob.class); jobDetail.setJobDataMap(jobData); if (!StringUtils.isBlank(description)) { jobDetail.setDescription(description); } scheduler.getListenerManager().addJobListener( new MessageServiceExecutorJobListener()); SimpleTriggerImpl trigger = new SimpleTriggerImpl("Exception_Message_Trigger " + Math.random(), "Exception Messaging", messageCopy .getQueueDate()); trigger.setJobDataMap(jobData);// 1.6 bug required or derby will choke scheduler.scheduleJob(jobDetail, trigger); }
Example 6
Source File: HRCronTriggerRunner.java From NewsRecommendSystem with MIT License | 5 votes |
public void task(List<Long> users,String cronExpression) throws SchedulerException { // Initiate a Schedule Factory SchedulerFactory schedulerFactory = new StdSchedulerFactory(); // Retrieve a scheduler from schedule factory Scheduler scheduler = schedulerFactory.getScheduler(); // Initiate JobDetail with job name, job group, and executable job class JobDetailImpl jobDetailImpl = new JobDetailImpl(); jobDetailImpl.setJobClass(HRJob.class); jobDetailImpl.setKey(new JobKey("HRJob1")); jobDetailImpl.getJobDataMap().put("users",users); // Initiate CronTrigger with its name and group name CronTriggerImpl cronTriggerImpl = new CronTriggerImpl(); cronTriggerImpl.setName("HRCronTrigger1"); try { // setup CronExpression CronExpression cexp = new CronExpression(cronExpression); // Assign the CronExpression to CronTrigger cronTriggerImpl.setCronExpression(cexp); } catch (Exception e) { e.printStackTrace(); } // schedule a job with JobDetail and Trigger scheduler.scheduleJob(jobDetailImpl, cronTriggerImpl); // start the scheduler scheduler.start(); }
Example 7
Source File: FileBasedSessionManager.java From centraldogma with Apache License 2.0 | 5 votes |
private Scheduler createScheduler(String cronExpr) throws SchedulerException { // The scheduler can be started and stopped several times in JUnit tests, but Quartz holds // every scheduler instances in a singleton SchedulerRepository. So it's possible to pick up // the scheduler which is going to be stopped if we use the same instance name for every scheduler, // because CentralDogmaExtension stops the server asynchronously using another thread. final String myInstanceId = String.valueOf(hashCode()); final Properties cfg = new Properties(); cfg.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore"); cfg.setProperty("org.quartz.scheduler.instanceName", FileBasedSessionManager.class.getSimpleName() + '@' + myInstanceId); cfg.setProperty("org.quartz.scheduler.skipUpdateCheck", "true"); cfg.setProperty("org.quartz.threadPool.threadCount", "1"); final Scheduler scheduler = new StdSchedulerFactory(cfg).getScheduler(); final JobDetail job = newJob(ExpiredSessionDeletingJob.class) .usingJobData(newJobDataMap(ImmutableMap.of(ROOT_DIR, rootDir))) .build(); final Trigger trigger = newTrigger() .withIdentity(myInstanceId, ExpiredSessionDeletingJob.class.getSimpleName()) .withSchedule(cronSchedule(cronExpr)) .build(); scheduler.scheduleJob(job, trigger); return scheduler; }
Example 8
Source File: ScheduledJobs.java From flowchat with GNU General Public License v3.0 | 5 votes |
public static void start() { // Another try { // Grab the Scheduler instance from the Factory Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // and start it off scheduler.start(); JobDetail fetchFromReddit = newJob(RedditImporter.class) .build(); // Trigger the job to run now, and then repeat every x minutes Trigger fetchFromRedditTrigger = newTrigger() .startNow() .withSchedule(simpleSchedule() .withIntervalInHours(4) .repeatForever()) .build(); // Tell quartz to schedule the job using our trigger scheduler.scheduleJob(fetchFromReddit, fetchFromRedditTrigger); } catch (SchedulerException se) { se.printStackTrace(); } }
Example 9
Source File: DaemonTaskScheduler.java From shardingsphere-elasticjob-cloud with Apache License 2.0 | 5 votes |
private void scheduleJob(final Scheduler scheduler, final JobDetail jobDetail, final String triggerIdentity, final String cron) { try { if (!scheduler.checkExists(jobDetail.getKey())) { scheduler.scheduleJob(jobDetail, createTrigger(triggerIdentity, cron)); } scheduler.start(); RUNNING_SCHEDULERS.putIfAbsent(scheduler.getSchedulerName(), scheduler); } catch (final SchedulerException ex) { throw new JobSystemException(ex); } }
Example 10
Source File: CallMonitor.java From openhab1-addons with Eclipse Public License 2.0 | 5 votes |
/** * Reset the connection to fbox periodically. */ public void setupReconnectJob() { try { // String cronPattern = "0 0 0 * * ?"; //every day // String cronPattern = "0 * * * * ?"; //every minute String cronPattern = "0 0 0/2 * * ?"; // every 2 hrs Scheduler sched = StdSchedulerFactory.getDefaultScheduler(); JobKey jobKey = jobKey("Reconnect", "FritzBox"); TriggerKey triggerKey = triggerKey("Reconnect", "FritzBox"); if (sched.checkExists(jobKey)) { logger.debug("reconnection job already exists"); } else { CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronPattern); JobDetail job = newJob(ReconnectJob.class).withIdentity(jobKey).build(); CronTrigger trigger = newTrigger().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); sched.scheduleJob(job, trigger); logger.debug("Scheduled reconnection job to FritzBox: {}", cronPattern); } } catch (SchedulerException e) { logger.warn("Could not create daily reconnection job", e); } }
Example 11
Source File: CBCronTriggerRunner.java From NewsRecommendSystem with MIT License | 5 votes |
public void task(List<Long> users,String cronExpression) throws SchedulerException { // Initiate a Schedule Factory SchedulerFactory schedulerFactory = new StdSchedulerFactory(); // Retrieve a scheduler from schedule factory Scheduler scheduler = schedulerFactory.getScheduler(); // Initiate JobDetail with job name, job group, and executable job class JobDetailImpl jobDetailImpl = new JobDetailImpl(); jobDetailImpl.setJobClass(CBJob.class); jobDetailImpl.setKey(new JobKey("CBJob1")); jobDetailImpl.getJobDataMap().put("users", users); // Initiate CronTrigger with its name and group name CronTriggerImpl cronTriggerImpl = new CronTriggerImpl(); cronTriggerImpl.setName("CBCronTrigger1"); try { // setup CronExpression CronExpression cexp = new CronExpression(cronExpression); // Assign the CronExpression to CronTrigger cronTriggerImpl.setCronExpression(cexp); } catch (Exception e) { e.printStackTrace(); } // schedule a job with JobDetail and Trigger scheduler.scheduleJob(jobDetailImpl, cronTriggerImpl); // start the scheduler scheduler.start(); }
Example 12
Source File: SchedulerUtil.java From OpenFalcon-SuitAgent with Apache License 2.0 | 5 votes |
/** * 执行计划任务 * @param job * @param trigger * @return * @throws SchedulerException */ public static ScheduleJobResult executeScheduleJob(JobDetail job, Trigger trigger) throws SchedulerException { ScheduleJobResult scheduleJobResult = new ScheduleJobResult(); //判断是否满足计划任务的创建条件 if(job.getKey() == null || trigger.getKey() == null || job.getJobDataMap() == null){ scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.FAILED); //不满足计划任务的创建条件,返回scheduleJobResult值类 return scheduleJobResult; } scheduleJobResult.setJobDetail(job); scheduleJobResult.setTrigger(trigger); //开始分配计划任务 Scheduler scheduler = SchedulerFactory.getScheduler(); //开始判断是否存在相同的计划任务 if(scheduler.checkExists(job.getKey())){ log.info("存在相同的计划任务:{}",job.getKey()); scheduler.deleteJob(job.getKey()); scheduleJobResult.setJobKey(job.getKey()); scheduleJobResult.setTriggerKey(trigger.getKey()); scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.ISEXIST); scheduler.scheduleJob(job,trigger); scheduler.start(); }else{ scheduler.scheduleJob(job,trigger); scheduler.start(); scheduleJobResult.setJobKey(job.getKey()); scheduleJobResult.setTriggerKey(trigger.getKey()); scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.SUCCESS); } //计划任务分配成功 return scheduleJobResult; }
Example 13
Source File: SchedulerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testScheduleMultipleTriggersForAJob() throws SchedulerException { JobDetail job = newJob(TestJob.class).withIdentity("job1", "group1").build(); Trigger trigger1 = newTrigger() .withIdentity("trigger1", "group1") .startNow() .withSchedule( SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1) .repeatForever()) .build(); Trigger trigger2 = newTrigger() .withIdentity("trigger2", "group1") .startNow() .withSchedule( SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1) .repeatForever()) .build(); Set<Trigger> triggersForJob = new HashSet<Trigger>(); triggersForJob.add(trigger1); triggersForJob.add(trigger2); Scheduler sched = createScheduler("testScheduleMultipleTriggersForAJob", 5); sched.scheduleJob(job, triggersForJob, true); List<? extends Trigger> triggersOfJob = sched.getTriggersOfJob(job.getKey()); assertEquals(2, triggersOfJob.size()); assertTrue(triggersOfJob.contains(trigger1)); assertTrue(triggersOfJob.contains(trigger2)); sched.shutdown(true); }
Example 14
Source File: JobTrigger.java From spring-cloud-shop with MIT License | 5 votes |
/** * 创建任务 * * @param scheduler scheduler * @param job job * @param params params */ public static void createJob(Scheduler scheduler, JobInfo job, Map<String, Object> params) throws SchedulerException { Class<? extends Job> jobClass = JobQuartzJobBean.class; // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getJobName(), job.getJobGroup()).build(); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCron()); // 按新的cron表达式构建一个新的trigger Trigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup()) .withSchedule(scheduleBuilder).build(); scheduler.scheduleJob(jobDetail, trigger); }
Example 15
Source File: SchedulerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testShutdownWithWaitIsClean() throws Exception { final AtomicBoolean shutdown = new AtomicBoolean(false); List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>()); CyclicBarrier barrier = new CyclicBarrier(2); final Scheduler scheduler = createScheduler("testShutdownWithWaitIsClean", 8); try { scheduler.getContext().put(BARRIER, barrier); scheduler.getContext().put(DATE_STAMPS, jobExecTimestamps); scheduler.start(); scheduler.addJob(newJob().ofType(TestJobWithSync.class).withIdentity("job").storeDurably().build(), false); scheduler.scheduleJob(newTrigger().forJob("job").startNow().build()); while (scheduler.getCurrentlyExecutingJobs().isEmpty()) { Thread.sleep(50); } } finally { Thread t = new Thread() { @Override public void run() { try { scheduler.shutdown(true); shutdown.set(true); } catch (SchedulerException ex) { throw new RuntimeException(ex); } } }; t.start(); Thread.sleep(1000); assertFalse(shutdown.get()); barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); t.join(); } }
Example 16
Source File: ScheduleManager.java From uyuni with GNU General Public License v2.0 | 5 votes |
private void scheduleJob(Scheduler sched, String name, int mode, long interval, Class task, JobDataMap data) throws SchedulerException { Trigger t = createTrigger(name, updateIndexGroupName, mode, interval); JobBuilder d = newJob(task).withIdentity(name, updateIndexGroupName); d.usingJobData(data); sched.scheduleJob(d.build(), t); }
Example 17
Source File: ScheduleUtils.java From supplierShop with MIT License | 5 votes |
/** * 创建定时任务 */ public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException { Class<? extends Job> jobClass = getQuartzJobClass(job); // 构建job信息 Long jobId = job.getJobId(); String jobGroup = job.getJobGroup(); JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId, jobGroup)).build(); // 表达式调度构建器 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression()); cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder); // 按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup)) .withSchedule(cronScheduleBuilder).build(); // 放入参数,运行时的方法可以获取 jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job); // 判断是否存在 if (scheduler.checkExists(getJobKey(jobId, jobGroup))) { // 防止创建时存在数据问题 先移除,然后在执行创建操作 scheduler.deleteJob(getJobKey(jobId, jobGroup)); } scheduler.scheduleJob(jobDetail, trigger); // 暂停任务 if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) { scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); } }
Example 18
Source File: SimpleExample.java From fixflow with Apache License 2.0 | 4 votes |
public void run() throws Exception { Logger log = LoggerFactory.getLogger(SimpleExample.class); log.info("------- Initializing ----------------------"); // First we must get a reference to a scheduler SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); log.info("------- Initialization Complete -----------"); // computer a time that is on the next round minute Date runTime = evenMinuteDate(new Date()); log.info("------- Scheduling Job -------------------"); // define the job and tie it to our HelloJob class JobDetail job = newJob(HelloJob.class) .withIdentity("job1", "group1") .build(); // Trigger the job to run on the next round minute Trigger trigger = newTrigger() .withIdentity("trigger1", "group1") .withIdentity(new TriggerKey("mytrigger")) .startAt(runTime) .build(); // Tell quartz to schedule the job using our trigger sched.scheduleJob(job, trigger); log.info(job.getKey() + " will run at: " + runTime); // Start up the scheduler (nothing can actually run until the // scheduler has been started) sched.start(); log.info("------- Started Scheduler -----------------"); // wait long enough so that the scheduler as an opportunity to // run the job! log.info("------- Waiting 5 seconds... -------------"); try { // wait 65 seconds to show job Thread.sleep(5L * 1000L); // executing... } catch (Exception e) { } // shut down the scheduler log.info("------- Shutting Down ---------------------"); sched.shutdown(true); log.info("------- Shutdown Complete -----------------"); }
Example 19
Source File: QuartzManager.java From quartz-web with Apache License 2.0 | 4 votes |
public void addTriggerForJob(String schedulerName, Trigger trigger) throws SchedulerException { Assert.notNull(trigger, "trigger can not be null"); Scheduler scheduler = this.getAssertScheduler(schedulerName); scheduler.scheduleJob(trigger); }
Example 20
Source File: Main.java From billow with Apache License 2.0 | 4 votes |
private Main(Config config) throws Exception { log.info("Startup..."); try { System.out.println(Resources.toString(getResource("banner.txt"), Charsets.UTF_8)); } catch (IllegalArgumentException | IOException e) { log.debug("No banner.txt", e); } final MetricRegistry metricRegistry = new MetricRegistry(); final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); log.info("Creating database"); final Config awsConfig = config.getConfig("aws"); final Long refreshRate = awsConfig.getDuration("refreshRate", TimeUnit.MILLISECONDS); final AWSDatabaseHolder dbHolder = new AWSDatabaseHolder(awsConfig); final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.getContext().put(AWSDatabaseHolderRefreshJob.DB_KEY, dbHolder); scheduler.start(); final SimpleTrigger trigger = newTrigger(). withIdentity(AWSDatabaseHolderRefreshJob.NAME). startNow(). withSchedule(simpleSchedule().withIntervalInMilliseconds(refreshRate).repeatForever()). build(); final JobDetail jobDetail = newJob(AWSDatabaseHolderRefreshJob.class). withIdentity(AWSDatabaseHolderRefreshJob.NAME). build(); scheduler.scheduleJob(jobDetail, trigger); log.info("Creating age health check"); healthCheckRegistry.register("DB", new HealthCheck() { @Override protected Result check() throws Exception { return dbHolder.healthy(); } }); log.info("Creating HTTP servers"); final Server mainServer = new Server(config.getInt("mainPort")); final Server adminServer = new Server(config.getInt("adminPort")); configureConnectors(mainServer); configureConnectors(adminServer); log.info("Creating HTTP handlers"); final Handler mainHandler = new Handler(metricRegistry, dbHolder, refreshRate); final InstrumentedHandler instrumentedHandler = new InstrumentedHandler(metricRegistry); instrumentedHandler.setHandler(mainHandler); mainServer.setHandler(instrumentedHandler); final ServletContextHandler adminHandler = new ServletContextHandler(); adminHandler.addServlet(new ServletHolder(new AdminServlet()), "/*"); final ServletContext adminContext = adminHandler.getServletContext(); adminContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry); adminContext.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry); adminServer.setHandler(adminHandler); log.info("Starting HTTP servers"); adminServer.start(); mainServer.start(); log.info("Joining..."); mainServer.join(); adminServer.join(); log.info("Shutting down scheduler..."); scheduler.shutdown(); log.info("We're done!"); }