Java Code Examples for org.quartz.Scheduler#shutdown()
The following examples show how to use
org.quartz.Scheduler#shutdown() .
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: BaseApplication.java From simple-robot-core with Apache License 2.0 | 7 votes |
/** * 默认情况下会执行{@link DependCenter}的close方法。 */ @Override public final void close(){ if(!closed){ doClose(); HttpClientHelper.clear(); this.listenerFilter.close(); dependCenter.close(); BotRuntime.close(); final Collection<Scheduler> allSchedulers; try { allSchedulers = this.stdSchedulerFactory.getAllSchedulers(); for (Scheduler scheduler : allSchedulers) { scheduler.shutdown(true); } } catch (SchedulerException e) { throw new RobotRuntimeException(e); } closed = true; System.gc(); } }
Example 2
Source File: CronService.java From aion-germany with GNU General Public License v3.0 | 6 votes |
public void shutdown() { Scheduler localScheduler; synchronized (this) { if (scheduler == null) { return; } localScheduler = scheduler; scheduler = null; runnableRunner = null; } try { localScheduler.shutdown(false); } catch (SchedulerException e) { log.error("Failed to shutdown CronService correctly", e); } }
Example 3
Source File: SchedulerTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Test public void testShutdownWithoutWaitIsUnclean() throws Exception { CyclicBarrier barrier = new CyclicBarrier(2); Scheduler scheduler = createScheduler("testShutdownWithoutWaitIsUnclean", 8); try { scheduler.getContext().put(BARRIER, barrier); scheduler.start(); scheduler.addJob(newJob().ofType(UncleanShutdownJob.class).withIdentity("job").storeDurably().build(), false); scheduler.scheduleJob(newTrigger().forJob("job").startNow().build()); while (scheduler.getCurrentlyExecutingJobs().isEmpty()) { Thread.sleep(50); } } finally { scheduler.shutdown(false); } barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); Thread jobThread = (Thread) scheduler.getContext().get(JOB_THREAD); assertThat(jobThread, notNullValue()); jobThread.join(TimeUnit.SECONDS.toMillis(TEST_TIMEOUT_SECONDS)); }
Example 4
Source File: SchedulerTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Test public void testAbilityToFireImmediatelyWhenStartedAfter() throws Exception { List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>()); CyclicBarrier barrier = new CyclicBarrier(2); Scheduler sched = createScheduler("testAbilityToFireImmediatelyWhenStartedAfter", 5); sched.getContext().put(BARRIER, barrier); sched.getContext().put(DATE_STAMPS, jobExecTimestamps); JobDetail job1 = JobBuilder.newJob(TestJobWithSync.class).withIdentity("job1").build(); Trigger trigger1 = TriggerBuilder.newTrigger().forJob(job1).build(); long sTime = System.currentTimeMillis(); sched.scheduleJob(job1, trigger1); sched.start(); barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); sched.shutdown(true); long fTime = jobExecTimestamps.get(0); assertTrue("Immediate trigger did not fire within a reasonable amount of time.", (fTime - sTime < 7000L)); // This is dangerously subjective! but what else to do? }
Example 5
Source File: ShutdownHookPlugin.java From AsuraFramework with Apache License 2.0 | 6 votes |
/** * <p> * Called during creation of the <code>Scheduler</code> in order to give * the <code>SchedulerPlugin</code> a chance to initialize. * </p> * * @throws SchedulerConfigException * if there is an error initializing. */ public void initialize(String name, final Scheduler scheduler) throws SchedulerException { this.name = name; this.scheduler = scheduler; getLog().info("Registering Quartz shutdown hook."); Thread t = new Thread("Quartz Shutdown-Hook " + scheduler.getSchedulerName()) { public void run() { getLog().info("Shutting down Quartz..."); try { scheduler.shutdown(isCleanShutdown()); } catch (SchedulerException e) { getLog().info( "Error shutting down Quartz: " + e.getMessage(), e); } } }; Runtime.getRuntime().addShutdownHook(t); }
Example 6
Source File: ShutdownHookPlugin.java From lams with GNU General Public License v2.0 | 6 votes |
/** * <p> * Called during creation of the <code>Scheduler</code> in order to give * the <code>SchedulerPlugin</code> a chance to initialize. * </p> * * @throws SchedulerConfigException * if there is an error initializing. */ public void initialize(String name, final Scheduler scheduler, ClassLoadHelper classLoadHelper) throws SchedulerException { getLog().info("Registering Quartz shutdown hook."); Thread t = new Thread("Quartz Shutdown-Hook " + scheduler.getSchedulerName()) { @Override public void run() { getLog().info("Shutting down Quartz..."); try { scheduler.shutdown(isCleanShutdown()); } catch (SchedulerException e) { getLog().info( "Error shutting down Quartz: " + e.getMessage(), e); } } }; Runtime.getRuntime().addShutdownHook(t); }
Example 7
Source File: QuartzPluginIT.java From glowroot with Apache License 2.0 | 6 votes |
@Override public void executeApp() throws Exception { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); JobDetail job; Trigger trigger; try { job = createJob2x(); trigger = createTrigger2x(); } catch (ClassNotFoundException e) { job = createJob1x(); trigger = createTrigger1x(); } scheduler.scheduleJob(job, trigger); SECONDS.sleep(1); scheduler.shutdown(); }
Example 8
Source File: SchedulerInit.java From cerberus-source with GNU General Public License v3.0 | 6 votes |
@PreDestroy public void closeScheduler() { try { LOG.info("Removing all Schedule entries."); Collection<Scheduler> myCollectionScheduller = schFactory.getAllSchedulers(); Iterator it = myCollectionScheduller.iterator(); for (Scheduler mySched : myCollectionScheduller) { mySched.clear(); mySched.shutdown(true); } LOG.info("end of Removing all Schedule entries."); } catch (Exception e) { LOG.error("Failed to clear Scheduler entries."); LOG.error(e); } }
Example 9
Source File: QuartzTest.java From thinking-in-spring with Apache License 2.0 | 5 votes |
public static void main(String[] args) { try { // 创建scheduler Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // 定义一个Trigger Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1") // 定义name/group .startNow() // 一旦加入scheduler,立即生效 .withSchedule(simpleSchedule() // 使用SimpleTrigger .withIntervalInSeconds(1) // 每隔一秒执行一次 .repeatForever()) // 一直执行,奔腾到老不停歇 .build(); // 定义一个JobDetail JobDetail job = newJob(HelloQuartz.class) // 定义Job类为HelloQuartz类,这是真正的执行逻辑所在 .withIdentity("job1", "group1") // 定义name/group .usingJobData("name", "quartz") // 定义属性 .build(); // 加入这个调度 scheduler.scheduleJob(job, trigger); // 启动 scheduler.start(); // 运行一段时间后关闭 Thread.sleep(10000); scheduler.shutdown(true); } catch (Exception e) { e.printStackTrace(); } }
Example 10
Source File: TestJobGlobalListener.java From javamelody with Apache License 2.0 | 5 votes |
/** Test. * @throws SchedulerException e * @throws InterruptedException e */ @Test public void testJobGlobalListener() throws SchedulerException, InterruptedException { final Counter jobCounter = JobGlobalListener.getJobCounter(); jobCounter.clear(); jobCounter.setDisplayed(true); // job quartz JobGlobalListener.initJobGlobalListener(); //Grab the Scheduler instance from the Factory final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); try { // and start it off scheduler.start(); final Random random = new Random(); // on lance 10 jobs pour être à peu près sûr qu'il y en a un qui fait une erreur // (aléatoirement il y en a 2/10 qui font une erreur) for (int i = 0; i < 10; i++) { //Define job instance final JobDetail job = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class); //Define a Trigger that will fire "now" final Trigger trigger = new SimpleTrigger("trigger" + random.nextInt(), null, new Date()); //Schedule the job with the trigger scheduler.scheduleJob(job, trigger); } // JobTestImpl fait un sleep de 2s au plus, donc on attend les jobs pour les compter Thread.sleep(3000); assertTrue("requestsCount", jobCounter.getRequestsCount() > 0); } finally { scheduler.shutdown(); JobGlobalListener.destroyJobGlobalListener(); } }
Example 11
Source File: SchedulerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testDurableStorageFunctions() throws Exception { Scheduler sched = createScheduler("testDurableStorageFunctions", 2); try { // test basic storage functions of scheduler... JobDetail job = newJob() .ofType(TestJob.class) .withIdentity("j1") .storeDurably() .build(); assertFalse("Unexpected existence of job named 'j1'.", sched.checkExists(jobKey("j1"))); sched.addJob(job, false); assertTrue("Unexpected non-existence of job named 'j1'.", sched.checkExists(jobKey("j1"))); JobDetail nonDurableJob = newJob() .ofType(TestJob.class) .withIdentity("j2") .build(); try { sched.addJob(nonDurableJob, false); fail("Storage of non-durable job should not have succeeded."); } catch (SchedulerException expected) { assertFalse("Unexpected existence of job named 'j2'.", sched.checkExists(jobKey("j2"))); } sched.addJob(nonDurableJob, false, true); assertTrue("Unexpected non-existence of job named 'j2'.", sched.checkExists(jobKey("j2"))); } finally { sched.shutdown(true); } }
Example 12
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 13
Source File: DaemonTaskScheduler.java From shardingsphere-elasticjob-cloud with Apache License 2.0 | 5 votes |
/** * Shutdown scheduling the task. * * @param taskID task id */ public static void shutdown(final Protos.TaskID taskID) { Scheduler scheduler = RUNNING_SCHEDULERS.remove(taskID.getValue()); if (null != scheduler) { try { scheduler.shutdown(); } catch (final SchedulerException ex) { throw new JobSystemException(ex); } } }
Example 14
Source File: AbstractSiteActivityTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
@Before public void setUp() throws Exception { applicationContext = ApplicationContextHelper.getApplicationContext(); String testid = ""+System.currentTimeMillis(); // Let's shut down the scheduler so that we aren't competing with the scheduled versions of the post lookup and // feed generator jobs Scheduler scheduler = (Scheduler) applicationContext.getBean("schedulerFactory"); scheduler.shutdown(); // Get the required services this.activityService = (ActivityService)applicationContext.getBean("activityService"); this.siteService = (SiteService)applicationContext.getBean("SiteService"); this.authenticationService = (MutableAuthenticationService)applicationContext.getBean("AuthenticationService"); this.personService = (PersonService)applicationContext.getBean("PersonService"); this.nodeArchiveService = (NodeArchiveService)applicationContext.getBean("nodeArchiveService"); LocalFeedTaskProcessor feedProcessor = null; // alternative: would need to add subsystem context to config location (see above) //this.postLookup = (PostLookup)applicationContext.getBean("postLookup"); //this.feedGenerator = (FeedGenerator)applicationContext.getBean("feedGenerator"); //feedProcessor = (LocalFeedTaskProcessor)applicationContext.getBean("feedTaskProcessor"); ChildApplicationContextFactory activitiesFeed = (ChildApplicationContextFactory)applicationContext.getBean("ActivitiesFeed"); ApplicationContext activitiesFeedCtx = activitiesFeed.getApplicationContext(); this.postLookup = (PostLookup)activitiesFeedCtx.getBean("postLookup"); this.feedGenerator = (FeedGenerator)activitiesFeedCtx.getBean("feedGenerator"); feedProcessor = (LocalFeedTaskProcessor)activitiesFeedCtx.getBean("feedTaskProcessor"); List<String> templateSearchPaths = new ArrayList<String>(1); templateSearchPaths.add(TEST_TEMPLATES_LOCATION); feedProcessor.setTemplateSearchPaths(templateSearchPaths); feedProcessor.setUseRemoteCallbacks(false); site1 = "test_site1_" + testid; site2 = "test_site2_" + testid; site3 = "test_site3_" + testid; user1 = "Test_User1_" + testid; user2 = "Test_User2_" + testid; user3 = "Test_User3_" + testid; user4 = "Test_User4_" + testid; // create users login(ADMIN_USER, ADMIN_PW); createUser(user1, USER_PW); createUser(user2, USER_PW); createUser(user3, USER_PW); createUser(user4, USER_PW); // create sites // create public site createSite(site1, true); // create private sites createSite(site2, false); createSite(site3, false); }
Example 15
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!"); }
Example 16
Source File: QuartzTest.java From fixflow with Apache License 2.0 | 4 votes |
public void testCronTrigger() throws SchedulerException { // SchedulerFactory // schedulerFactory=scheduleService.getSchedulerFactory(); // Scheduler scheduler=schedulerFactory.getScheduler(); Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); assertNotNull(scheduler); scheduler.start(); JobDetail job = newJob(SimpleJob.class).withIdentity("job1", "group1") .build(); Date nowDate = new Date(); long startDate = nowDate.getTime() + (24 * 60 * 60 * 1000); Date triggerStartTime = new Date(startDate); @SuppressWarnings("deprecation") int hour = nowDate.getHours(); String cronExpr = "* * 7/24 * * ?"; cronExpr = "* * "+hour+"/24 ? * 2-6"; System.out.println("cronExpr:" + cronExpr); CronTrigger trigger = newTrigger().withIdentity("trigger3", "group1") .withSchedule(cronSchedule(cronExpr)).startAt(triggerStartTime) .forJob("job1", "group1").build(); scheduler.scheduleJob(job, trigger); // trigger. Date date = trigger.getNextFireTime(); // trigger. // trigger.get SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("下次执行时间:" + df.format(date)); Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, +24); System.out.println("Calendar:" + cal.get(Calendar.HOUR_OF_DAY)); scheduler.shutdown(); assertTrue(true); }
Example 17
Source File: QuartzManager.java From quartz-web with Apache License 2.0 | 4 votes |
public void schedulerShutdown(String schedulerName) throws SchedulerException { Scheduler scheduler = this.getAssertScheduler(schedulerName); if (!scheduler.isShutdown()) { scheduler.shutdown(); } }
Example 18
Source File: ShowScheduler.java From iaf with Apache License 2.0 | 4 votes |
@PUT @RolesAllowed({"IbisDataAdmin", "IbisAdmin", "IbisTester"}) @Path("/schedules/") @Relation("schedules") @Produces(MediaType.APPLICATION_JSON) public Response updateScheduler(LinkedHashMap<String, Object> json) throws ApiException { Scheduler scheduler = getScheduler(); String action = null; for (Entry<String, Object> entry : json.entrySet()) { String key = entry.getKey(); if(key.equalsIgnoreCase("action")) { action = entry.getValue().toString(); } } try { String commandIssuedBy = servletConfig.getInitParameter("remoteHost"); commandIssuedBy += servletConfig.getInitParameter("remoteAddress"); commandIssuedBy += servletConfig.getInitParameter("remoteUser"); if (action.equalsIgnoreCase("start")) { if(scheduler.isInStandbyMode() || scheduler.isShutdown()) { scheduler.start(); log.info("start scheduler:" + new Date() + commandIssuedBy); } else { throw new ApiException("Failed to start scheduler"); } } else if (action.equalsIgnoreCase("pause")) { if(scheduler.isStarted()) { scheduler.standby(); log.info("pause scheduler:" + new Date() + commandIssuedBy); } else { throw new ApiException("Failed to pause scheduler"); } } else if (action.equalsIgnoreCase("stop")) { if(scheduler.isStarted() || scheduler.isInStandbyMode()) { scheduler.shutdown(); log.info("shutdown scheduler:" + new Date() + commandIssuedBy); } else { throw new ApiException("Failed to stop scheduler"); } } else { return Response.status(Response.Status.BAD_REQUEST).build(); } } catch (Exception e) { log.error("unable to run action ["+action+"]",e); } return Response.status(Response.Status.OK).build(); }
Example 19
Source File: SchedulerTest.java From nexus-public with Eclipse Public License 1.0 | 3 votes |
@Test public void testAbilityToFireImmediatelyWhenStartedBefore() throws Exception { List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>()); CyclicBarrier barrier = new CyclicBarrier(2); Scheduler sched = createScheduler("testAbilityToFireImmediatelyWhenStartedBefore", 5); sched.getContext().put(BARRIER, barrier); sched.getContext().put(DATE_STAMPS, jobExecTimestamps); sched.start(); Thread.yield(); JobDetail job1 = JobBuilder.newJob(TestJobWithSync.class).withIdentity("job1").build(); Trigger trigger1 = TriggerBuilder.newTrigger().forJob(job1).build(); long sTime = System.currentTimeMillis(); sched.scheduleJob(job1, trigger1); barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); sched.shutdown(true); long fTime = jobExecTimestamps.get(0); assertTrue("Immediate trigger did not fire within a reasonable amount of time.", (fTime - sTime < 7000L)); // This is dangerously subjective! but what else to do? }
Example 20
Source File: SchedulerTest.java From nexus-public with Eclipse Public License 1.0 | 3 votes |
@Test public void testAbilityToFireImmediatelyWhenStartedBeforeWithTriggerJob() throws Exception { List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>()); CyclicBarrier barrier = new CyclicBarrier(2); Scheduler sched = createScheduler("testAbilityToFireImmediatelyWhenStartedBeforeWithTriggerJob", 5); sched.getContext().put(BARRIER, barrier); sched.getContext().put(DATE_STAMPS, jobExecTimestamps); sched.start(); Thread.yield(); JobDetail job1 = JobBuilder.newJob(TestJobWithSync.class).withIdentity("job1").storeDurably().build(); sched.addJob(job1, false); long sTime = System.currentTimeMillis(); sched.triggerJob(job1.getKey()); barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); sched.shutdown(true); long fTime = jobExecTimestamps.get(0); assertTrue("Immediate trigger did not fire within a reasonable amount of time.", (fTime - sTime < 7000L)); // This is dangerously subjective! but what else to do? }