@Timeout public void execute(Timer timer) { if (!VM_TIMER_INFO.equals(timer.getInfo())) { return; } List<ServiceInstance> instances = serviceInstanceService.getInstances(); for (ServiceInstance serviceInstance : instances) { try { final APPlatformController controller = APPlatformControllerFactory .getInstance(serviceInstance.getControllerId()); int vmsNumber = controller.getServersNumber(serviceInstance.getInstanceId(), serviceInstance.getSubscriptionId(), serviceInstance.getOrganizationId()); ServiceInstance updatedServiceInstance = serviceInstanceService.updateVmsNumber(serviceInstance, vmsNumber); serviceInstanceService.notifySubscriptionAboutVmsNumber(updatedServiceInstance); } catch (APPlatformException e) { logger.error("Subscription cannot be notified about VMs number: ", e); } } }
@Timeout public void timeout(Timer timer) { LOGGER.info("timeout() - (ENTER)"); Properties policy = policyProvider.getProperties(POLICY_SUBJECT); int ttlSession = policyProvider.getIntProperty(policy, "account.maxSessionDuration", 0); if (ttlSession > 0) { Date startedBefore = new Date(System.currentTimeMillis() - (ttlSession * ONE_SECOND)); LOGGER.info("startedBefore: " + startedBefore); List<String> expired = findExpiredSessions(startedBefore); for (String sessionId : expired) { LOGGER.info("deleteing expired session: " + sessionId); deleteSession(sessionId); } } LOGGER.info("timeout() - (LEAVE)"); }
@Timeout public void createKindleMail(Timer timer) { try { Payload payload = (Payload)timer.getInfo(); BookEntry book = payload.getBook(); AppUser user = payload.getUser(); byte[] attachment = solrHandler.getMobiFormat(book.getId()).get(0).getMobi(); //1.Step Check if convert if (attachment == null) { convertEPubToMobi(book); attachment = solrHandler.getMobiFormat(book.getId()).get(0).getMobi(); } //2. Step Send Email String filename = book.getTitle() + "-" + book.getAuthor(); sendKindleMail(user, attachment, filename); } catch (SolrServerException | MessagingException | IOException | InterruptedException ex) { logger.error("failed to create Kindle mail.",ex); } }
@Timeout public void timeout(Timer timer) { if (propertyService.getBoolean("mail.reminder.active")) { log.info("Reminder activated."); List<SimpleApproval> simpleApprovals = simpleApprovalDAO.findOpenApprovalsProcessInstanceId(); for (SimpleApproval simpleApproval : simpleApprovals) { log.info("ProcessInstanceId: " + simpleApproval); // TODO: make the query more efficient List<Status> statusList = new ArrayList<Status>(); statusList.add(Status.InProgress); statusList.add(Status.Reserved); List<TaskSummary> tasks = runtimeDataService.getTasksByStatusByProcessInstanceId(simpleApproval.getProcessInstanceId(), statusList, null); if (tasks.size() > 1) { log.warning("More then one task for processInstanceId: " + simpleApproval.getProcessInstanceId()); } TaskSummary task = tasks.get(0); String actualOwner = task.getActualOwnerId(); sendReminderEmail(actualOwner, simpleApproval.getProcessInstanceId(), simpleApproval.getSubject()); } } else { log.warning("Reminder inactive!"); } }
@Timeout public void health(Timer timer) { LOGGER.config(() -> "health update: " + Calendar.getInstance().getTime()); LOGGER.config(() -> "Next: " + timer.getNextTimeout()); EurekaConfig eurekaConfig = new EurekaConfig(); eurekaConfig.setStatus("UP"); Entity<InstanceConfig> entity = Entity.entity(new InstanceConfig(eurekaConfig), MediaType.APPLICATION_JSON); Response response = ClientBuilder.newClient() .target(serviceUrl + "apps/" + applicationName + "/" + applicationName) .request() .put(entity); LOGGER.config(() -> "PUT resulted in: " + response.getStatus() + ", " + response.getEntity()); }
/** * Execute the job given as extra info to the timer object. * <p/> * @param timer */ @Timeout public void timeout(Timer timer) { Serializable jobId = timer.getInfo(); //Valid id? if (!(jobId instanceof Integer)) { logger.log(Level.WARNING, "Trying to run a scheduled execution, but info is not of integer class."); return; } //Valid job? Jobs job = jobFacade.findById((Integer) jobId); if (job == null) { logger.log(Level.WARNING, "Trying to run a job with non-existing id."); return; } try { //Yes! Now execute! executionController.start(job, job.getCreator()); } catch (IOException ex) { logger.log(Level.WARNING, "Exception while starting scheduled job " + job, ex); } }
@Timeout public void execute(Timer timer) { try { if (timer.getTimeRemaining() < 0) { logger.info("Skipping missed job timeout with id {}", timer.getInfo()); return; } } catch (NoMoreTimeoutsException e) { } Job job = em.find(Job.class, timer.getInfo()); if (job == null) { logger.info("Job with id {} not found. Cancelling...", timer.getInfo()); timer.cancel(); } else if (!job.isActivate()) { logger.info("Skipping execution of job {} because it is marked as inactive.", timer.getInfo()); } else { JobExecution execution = executor.createExecution(job); executor.execute(execution, job); } }
@Timeout private void sendTimeStep() { FcdTimeStep step = this.timeSteps.get(this.sequence); SocketResponse response = new SocketResponse(); response.timeStep = step; if(this.sendMovement(CarSocket.apiKey, this.sequence, step)) { response.message = "Successfully sent movement. Sequence number " + this.sequence + " of " + this.timeSteps.size(); } else { response.message = "Failed to send movement! Sequence number " + this.sequence + " of " + this.timeSteps.size(); } this.session.getAsyncRemote().sendText(this.xStream.toXML(response)); //this.gson.toJson(response)); if(this.sequence + 1 < this.timeSteps.size()) { this.setTimer((int)(this.timeSteps.get(sequence + 1).getTime() - step.getTime())); this.sequence++; } }
@Timeout public void timeout(Timer timer) { final Cache<String, ExecutionControl> cache = GlobalCache.get().getExecutionControls(); String info = (String) timer.getInfo(); try { int n = info.indexOf(' '); String execCtrlName = info.substring(0, n); int cycleNum = Integer.parseInt(info.substring(n + 1)); ExecutionControl execCtrl = cache.get(execCtrlName); if (execCtrl != null) execCtrl.onTimeout(cycleNum); else logger.log(Level.WARNING, "ExecutionControl " + execCtrlName + " not found."); } catch (ConcurrentAccessTimeoutException ex) { logger.warning(ex.getMessage()); } }
@Timeout public void startup(Timer timer) { try { userTransaction.begin(); log.log(Level.INFO, "Starting application..."); replayEvents(); startDispatchScheduler(); startSagaTracker(); userTransaction.commit(); } catch (NotSupportedException | SystemException | HeuristicMixedException | HeuristicRollbackException | IllegalStateException | RollbackException | SecurityException ex) { log.severe(ex.getMessage()); throw new RuntimeException(ex); } }
@Timeout @Interceptors(ExcludingInterceptor.class) private void timeout(Timer timer) { timerServiceCalled = true; interceptorResults += "@Timeout"; latch.countDown(); }
@Timeout public void timeout(Timer timer) { if (timer.equals(simulationTimer)){ sim.run(); } else if (timer.equals(hourlySalesTimer)){ hourlySalesGenerator.run(); } }
/** * Handles the timer event. */ @Timeout public void handleTimer(@SuppressWarnings("unused") Timer timer) { if (logFile != null) { handleOnChange(logFile); } }
@Timeout public void reconfigure() { this.monitoring = ClientBuilder. newClient(). target("http://localhost:8080/firehose/resources/configurations/"); this.configure("problematic503", "http://localhost:4848/monitoring/domain/server/http-service/server/request.json"); this.configure("problematicRollbacks", "http://localhost:4848/monitoring/domain/server/transaction-service/rolledbackcount.json"); this.configure("avgRequestProcessingTime", "http://localhost:4848/monitoring/domain/server/http-service/server/request/processingtime.json"); this.configure("countqueued1minuteaverage", "http://localhost:4848/monitoring/domain/server/network/connection-queue/countqueued1minuteaverage.json"); this.configure("echoExecutionTime", "http://localhost:4848/monitoring/domain/server/applications/problematic/Pings/bean-methods/echo-long-java.lang.String.json"); this.configure("currentThreadsBusy", "http://localhost:4848/monitoring/domain/server/network/http-listener-1/thread-pool/currentthreadsbusy.json"); this.configure("usedHeapSize", "http://localhost:4848/monitoring/domain/server/jvm/memory/usedheapsize-count.json"); }
@Timeout public void timeout(Timer timer) { Logger.getLogger(PingForLeaders.class.getName()).log(Level.INFO, "Timer fired at {0}", new Date()); /** * find top 10 trending groups */ Set<Tuple> zrangeByScoreWithScores = jedis.zrevrangeByScoreWithScores(LEADERBOARD_REDIS_KEY, Integer.MAX_VALUE, 1, 0, 10); Leaderboard lb = new Leaderboard(); for (Tuple tuple : zrangeByScoreWithScores) { lb.add(tuple.getElement(), String.valueOf(tuple.getScore())); } String json = null; try { json = mapper.writeValueAsString(lb); } catch (JsonProcessingException ex) { Logger.getLogger(PingForLeaders.class.getName()).log(Level.SEVERE, null, ex); } msgEvent.fire(json); }
@Timeout public void timeout(Timer timer) { try { log.info("create replenishment if needed"); sanityCheck(); } catch (Throwable e) { log.error(e.getMessage(), e); } }
/** * Timeout Method, which will start the frequent cleaning. * * @param timer Timer information, useful for logging */ @Timeout public void doCleanup(final Timer timer) { LOG.info("Timeout occurred, will start the Cleanup"); final long start = System.nanoTime(); // For the suspension & deleting, we need to use an Authentication // Object for history information. We're using the System account for // this. Even if nothing is to be deleted, we're still fetching the // record here, since the Cron job is only running once every 24 hours, // we do not care much for performance problems. final UserEntity system = entityManager.find(UserEntity.class, InternalConstants.SYSTEM_ACCOUNT); final Authentication authentication = new Authentication(system, timer.getInfo().toString()); // First, let's get rid of those pesky expired sessions. For more // information, see the Trac ticket #900. removeDeprecatedSessions(); // Second, we'll handle Offers which have expired. runExpiredOfferProcessing(); // third, we'll deal with accounts which are inactive. For more // information, see the Trac ticket #720. final int expired = removeUnusedNewAccounts(); final int suspended = suspendInactiveAccounts(authentication); final int deleted = deleteSuspendedAccounts(authentication); final DateFormat dateFormatter = new SimpleDateFormat(IWSConstants.DATE_TIME_FORMAT, IWSConstants.DEFAULT_LOCALE); final long duration = (System.nanoTime() - start) / 1000000; LOG.info("Cleanup took: {}ms (Users expired {}, suspended {} & deleted {}), next Timeout: {}", duration, expired, suspended, deleted, dateFormatter.format(timer.getNextTimeout())); }
@Timeout public void handleTimer(final Timer timer) { SchedulerTimerConfig config = (SchedulerTimerConfig) timer.getInfo(); log.info("run EE Timer " + config.getSchedulerName()); try { Context.internalRequestScope().setManaged(false); Context.start(); if (config.getPersistenceReference() != null) { setApplicationEntityManager(config.getPersistenceReference()); } Context.sessionScope().setUser("SchedulerTask-" + config.getSchedulerName()); EntityManager em = Context.internalRequestScope().getOrCreateEntityManager(false); TypedQuery<Controllable> q = em.createNamedQuery(Controllable.SEL_SCHED_BY_DATE, Controllable.class); q.setParameter("actuator", config.getSchedulerName()); q.setParameter("currentDate", new Date(), TemporalType.TIMESTAMP); List<Controllable> list = q.getResultList(); log.info(list.size() + " due scheduled business cases found"); for (Controllable co : list) { co.decrypt(); process(co); } } catch (Exception e) { log.error("Failed to execute EEScheduledTask Timer " + config.getSchedulerName() + ": " + e.getMessage(), e); } finally { Context.end(); } }
/** * When the timeout occurs, post the notifications from Github somewhere. */ @Timeout public void check() { try { for(final Post post : this.posts) { post.send(); } } catch (IOException e) { log.error("IOException when checking or sending notifications: ", e); } catch (AssertionError err) { log.error("Unexpected status response when checking or sending notifications: ", err); } }
@Timeout public void timeout(Timer timer) { try { logger.debug("Executing Timer "); BatchJobConfiguration jobConfig = (BatchJobConfiguration)timer.getInfo(); logger.debug("Executing Batch Job " + jobConfig.getType().getDisplayName()); BatchJobInterface batchJob = (BatchJobInterface)InitialContext.doLookup(jobConfig.getType().getModuleName()); batchJob.executeJob(timer); //Asynchronous method } catch(NamingException ex) { logger.error(ex,ex); } }
/** * Calculates statistics and stores them in the database. * * @param timer * timer that triggered the event */ @Timeout protected void onTimeout(Timer timer) { StatisticsCalculator proxy = ctx.getBusinessObject(StatisticsCalculator.class); logger.info("Statistics calculation started"); long start = System.currentTimeMillis(); proxy.calculateBasicStatistics(); proxy.calculateDataFileFormatStatistics(); proxy.calculateMetadataFormatStatistics(); logger.info("Statistics calculation finished (took " + (System.currentTimeMillis() - start) + " ms)"); }
/** * Checks the user certificates and reports the ones that are beyond expiration threshold. * * @param timer * timer that triggered the event */ @Timeout protected void onTimeout(Timer timer) { CertificateChecker proxy = ctx.getBusinessObject(CertificateChecker.class); logger.info("Certificate checking started"); long start = System.currentTimeMillis(); proxy.checkCertificates(); logger.info("Certificate checking finished (took " + (System.currentTimeMillis() - start) + " ms)"); }
/** * Handles all the timer events defined for this class. The event type can be obtained using the * {@link Timer#getInfo()} method. * * @param timer * timer that triggered the event */ @Timeout protected void onTimeout(Timer timer) { if (timer.getInfo() instanceof EventType) { switch ((EventType) timer.getInfo()) { case INITIALIZE_FORMAT_WORK: formatInitializer.initializeWork(); formatWorker.start(); break; case ACTIVATE_FORMAT_WORKER: formatWorker.activate(); break; case DEACTIVATE_FORMAT_WORKER: formatWorker.deactivate(); break; case ACTIVATE_INTEGRITY_WORKER: integrityWorker.activate(); break; case DEACTIVATE_INTEGRITY_WORKER: integrityWorker.deactivate(); break; default: throw new RuntimeException("Unexpected EventType value: " + timer.getInfo()); } } else if (timer.getInfo() instanceof PluginEvent) { PluginEvent event = (PluginEvent) timer.getInfo(); switch (event.type) { case ACTIVATE: pluginExecutor.start(event.pluginName); break; case DEACTIVATE: pluginExecutor.stop(event.pluginName); break; default: throw new RuntimeException("Unexpected PluginEventType value: " + event.type); } } }
@Timeout public void tick() { if (active) { System.out.println("Business fires event"); businessEvent.fire(new BusinessEvent("second = " + new Date().getSeconds())); } }
@Timeout public void doWork() { boolean enabled = Boolean.parseBoolean(System.getProperty("disqus.synchronization.enabled", "false")); if (enabled) { String apiKey = System.getProperty("disqus.apiKey"); String forum = System.getProperty("disqus.synchronization.forum"); disqusSynchronizationService.synchronizeComments(apiKey, forum); disqusSynchronizationService.deleteComments(apiKey, forum); } }
@Timeout @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) private void timeout(Timer timer) { try { clusterController.cleanupUnverifiedUsers(); } catch(Exception e) { LOG.log(Level.WARNING, "Failed to cleanup cluster agents. {0}", e.getMessage()); } }
@Timeout @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) private void timeout(Timer timer) { LOG.log(Level.INFO, "state timeout:{0}", new Object[]{state}); switch (state) { case SETUP: setup(timer); break; case DELA_VERSION: delaVersion(timer); break; case DELA_CONTACT: delaContact(timer); break; case REGISTER: hopsSiteRegister(timer); break; case HEAVY_PING: heavyPing(timer); break; case PING: ping(timer); break; default: throw new IllegalStateException("unknown state"); } }
/** * Sends the message out... * @param timer - timer */ @Timeout public void send(Timer timer) { if (timer.getInfo() instanceof Email) { Email email = (Email) timer.getInfo(); // Retrieve bidders/sellers and email… } }
@Timeout public void finishAuctionHandler(Timer timer) { Long articleId = (Long) timer.getInfo(); Article article = articleDao.findById(articleId); if (article == null) { throw new EJBException("Article is delete in the meantime. id: " + articleId); } ArrayList<Bid> sorted = sortBids(article); switch (sorted.size()) { case 0: // No bids article.setArticleState(ArticleState.UNSALEABE); break; case 1: // Only one bid Bid highest = sorted.get(0); article.setSuccessfulBid(highest); article.setBuyer(highest.getBidder()); article.setFinalPrice(article.getInitialPrice()); article.setArticleState(ArticleState.SOLD); break; default: // More bids. Use the bid with the highest price highest = sorted.get(sorted.size() - 1); Bid second = sorted.get(sorted.size() - 2); article.setFinalPrice(second.getAmount() + 1); article.setBuyer(highest.getBidder()); article.setSuccessfulBid(highest); article.setArticleState(ArticleState.SOLD); } articleDao.merge(article); System.out.println("===> Auction for " + article.getName() + " finished."); }