Java Code Examples for org.springframework.scheduling.annotation.Scheduled

The following are top voted examples for showing how to use org.springframework.scheduling.annotation.Scheduled. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: microservices-prototype   File: DataService.java   View source code 7 votes vote down vote up
@HystrixCommand(fallbackMethod = HYSTRIX_FALL_BACK,
        commandKey = HYSTRIX_COMMAND_KEY,
        groupKey = HYSTRIX_GROUP_KEY)
@Scheduled(fixedDelay = 60000)
public void indexedData() {

    log.info("SEARCH-SERVICE: Data indexer is starting to work.");

    currentPageIndex = getCurrentPageIndex();

    log.info("Current page for pushing is {}", currentPageIndex);

    long totalPage = tweetClient.getTweets().getMetadata().getTotalPages();

    for (long i = currentPageIndex; i <= totalPage; i++) {
        Runnable task = new PusherProcessor(tweetRepository, tweetClient, i);
        taskExecutor.execute(task);

        currentPageIndex = i++;

        saveCurrentPageIndex(i);
    }
}
 
Example 2
Project: lemon   File: TaskTimeoutJob.java   View source code 6 votes vote down vote up
@Scheduled(cron = "0/10 * * * * ?")
public void execute() throws Exception {
    logger.info("start");

    List<Task> tasks = processEngine.getTaskService().createTaskQuery()
            .list();

    for (Task task : tasks) {
        if (task.getDueDate() != null) {
            SendNoticeCmd sendNoticeCmd = new SendNoticeCmd(task.getId());
            processEngine.getManagementService().executeCommand(
                    sendNoticeCmd);
        }
    }

    logger.info("end");
}
 
Example 3
Project: stdds-monitor   File: DataScheduler.java   View source code 6 votes vote down vote up
@Scheduled(fixedRate = 60000)
@Transactional
public void purgeOldNotifications() {
	ExpirationConfiguration props = properties.getNotifications();
	String methodName = "purgeOldNotifications";
	PurgeMethods purgeMethod = new PurgeMethods() {

		@Override
		public long deleteByTime(long time) {
			return notRepo.deleteByTimeLessThanOrderByTimeDesc(time);
		}

		@Override
		public long deleteBySize(long max) {
			return 0;
		}
		
	};
	purgeData(methodName, props, purgeMethod);
}
 
Example 4
Project: flow-platform   File: AgentServiceImpl.java   View source code 6 votes vote down vote up
@Override
@Transactional(propagation = Propagation.NEVER)
@Scheduled(initialDelay = 10 * 1000, fixedDelay = SESSION_TIMEOUT_TASK_HEARTBEAT)
public void sessionTimeoutTask() {
    if (!taskConfig.isEnableAgentSessionTimeoutTask()) {
        return;
    }

    LOGGER.traceMarker("sessionTimeoutTask", "start");
    ZonedDateTime now = DateUtil.utcNow();

    for (Zone zone : zoneService.getZones()) {
        Collection<Agent> agents = listForOnline(zone.getName());
        for (Agent agent : agents) {
            if (agent.getSessionId() != null && isSessionTimeout(agent, now, zone.getAgentSessionTimeout())) {
                Cmd delSessionCmd = cmdService.create(new CmdInfo(agent.getPath(), CmdType.DELETE_SESSION, null));
                cmdDispatchService.dispatch(delSessionCmd);
                LOGGER.traceMarker("sessionTimeoutTask", "Send DELETE_SESSION to agent %s", agent);
            }
        }
    }

    LOGGER.traceMarker("sessionTimeoutTask", "end");
}
 
Example 5
Project: AngularAndSpring   File: ScheduledTask.java   View source code 6 votes vote down vote up
@Scheduled(fixedRate = 60000, initialDelay=15000)
	public void insertCoinbaseQuote() {
		Date start = new Date();
		WebClient wc = buildWebClient(URLCB);
		try {
			operations.insert(
					wc.get().uri("/exchange-rates?currency=BTC")
	                .accept(MediaType.APPLICATION_JSON).exchange()
	                .flatMap(response ->	response.bodyToMono(WrapperCb.class))
	                .flatMap(resp -> Mono.just(resp.getData()))
	                .flatMap(resp2 -> {log.info(resp2.getRates().toString()); return Mono.just(resp2.getRates());})
					).then().block(Duration.ofSeconds(3));
			log.info("CoinbaseQuote " + dateFormat.format(new Date()) + " " + (new Date().getTime()-start.getTime()) + "ms");
		} catch (Exception e) {
//			log.error("Coinbase insert error", e);
			log.error("Coinbase insert error "+ dateFormat.format(new Date()));
		}
	}
 
Example 6
Project: agile-wroking-backend   File: SendNotifyMessageJob.java   View source code 6 votes vote down vote up
@Scheduled(fixedDelay = 60 * 1000)
public void execute() {
	Date date = DateUtils.parse(DateUtils.format(new Date(), DateUtils.PATTERN_SIMPLE_DATE),
			DateUtils.PATTERN_SIMPLE_DATE);
	if (date.compareTo(this.date) > 0) {
		this.date = date;
		cache.clear();
	}

	String accessToken = getAccessToken();
	scheduleRepository.findByDate(date).forEach(s -> {
		if (cache.contains(new Long(s.getScheduleId().intValue()))) {
			return;
		}
		if (isNeedSendMessageNow(s)) {
			doSend(accessToken, s);
			cache.add(new Long(s.getScheduleId().intValue()));
		}
	});
}
 
Example 7
Project: app-ms   File: CachedDataProvider.java   View source code 6 votes vote down vote up
/**
 * Builds JWKS if necessary after 60 seconds, but only builds
 * {@value #MIN_NUMBER_OF_KEYS} at a time.
 */
@Scheduled(fixedDelay = 60000)
public void buildJwks() {

    int nCreated = 0;
    for (int i = 0; i < MAX_NUMBER_OF_KEYS; ++i) {
        final String cacheKey = String.valueOf(i);
        final JsonWebKey jwk = jwksCache.get(cacheKey, JsonWebKey.class);
        if (jwk == null && nCreated < MIN_NUMBER_OF_KEYS) {
            final RsaJsonWebKey newJwk = buildNewRsaKey();
            jwksCache.putIfAbsent(cacheKey, newJwk);
            ++nCreated;
            LOG.debug("Created new JWK kid={}", newJwk.getKeyId());
        }
    }

}
 
Example 8
Project: biblebot   File: PostService.java   View source code 6 votes vote down vote up
/**
 * Process all instance days that are not processed already, but are due
 *
 * “At minute 0 past every hour.”
 */
@Scheduled(cron = "${biblereadingplan.postservice.cron:0 0 */1 * * *}")
@Transactional
public void process() {
    validateService.scheduleAll();
    for (PlanInstanceDay instanceDay : planInstanceDayRepository
            .findAllByIsPostedIsFalseAndScheduledDateBeforeOrderByScheduledDateAsc(new Date())) {
        validateService.setDefaultValues(instanceDay.getDay());
        validateService.setDefaultValues(instanceDay);
        if (rocketChatPostService.post(instanceDay)) {
            instanceDay.setPosted(true);
            planInstanceDayRepository.save(instanceDay);
        } else {
            LOGGER.error("Could not post message.");
        }
    }
}
 
Example 9
Project: sentry   File: UserCountService.java   View source code 6 votes vote down vote up
@Scheduled(cron = "10 * * * * ?")
void storeUserCountMetrics() {
    ZonedDateTime timestamp = ZonedDateTime.now().truncatedTo(MINUTES);

    userCountRepository.save(
        metricRegistry.getHistograms((name, metric) -> name.startsWith("discord.ws.users"))
            .entrySet().stream()
            .map(entry -> Pair.of(extractTags(entry.getKey()), (long) entry.getValue().getSnapshot().getMean()))
            .map(pair -> new UserCount()
                .bot(pair.getKey()[0])
                .guild(pair.getKey()[1])
                .status(pair.getKey()[2])
                .value(pair.getValue())
                .timestamp(timestamp))
            .collect(Collectors.toList())
    );
}
 
Example 10
Project: spring-cloud-samples   File: ProductService.java   View source code 5 votes vote down vote up
/**
 */
@Scheduled(fixedRate = 10000)
public void autoCancel() {
	// 获取过期的资源
	final List<ProuctTcc> tccs = productTccRepositorie.expireReservation(2);
	tccs.forEach(tcc -> {
		cancel(tcc.getId());
	});
}
 
Example 11
Project: proxylive   File: ProcessorTasks.java   View source code 5 votes vote down vote up
@Scheduled(fixedDelay = 5 * 1000)//Every 5 seconds
public void killHLSStreams() {
    long now = new Date().getTime();
    Map<Thread, IStreamTask> HLSTasksFore = new HashMap(HLSTasks);
    for (Entry<Thread, IStreamTask> entry : HLSTasksFore.entrySet()) {
        HLSTask hlsTask = (HLSTask) entry.getValue();
        if (hlsTask.getLastAccess() != null) {
            long difference = (now - hlsTask.getLastAccess()) / 1000;
            if (difference > config.getFfmpeg().getHls().getTimeout()) {
                //Kill all stream processors using this task
                for (ClientInfo client : new ArrayList<>(streamProcessorsSession.getClientInfoList())) {
                    for (IStreamProcessor streamProcessor : new ArrayList<>(client.getStreams())) {
                        IStreamTask streamBindedTask = streamProcessor.getTask();
                        if (streamBindedTask == hlsTask) {
                            try {
                                streamProcessor.stop(false);
                                streamProcessorsSession.removeClientInfo(client, streamProcessor);
                            } catch (Exception ex) {
                            }
                        }
                    }
                }
            }
        }

    }
}
 
Example 12
Project: SkyEye   File: UploadTask.java   View source code 5 votes vote down vote up
/**
 * 上传到hdfs并删除相应的文件
 */
@Scheduled(cron = "${spring.upload.log.cron}")
private void upload() {
    String yesterday = this.getYesterday();
    LOGGER.info("开始上传到hdfs, 时间: {}", yesterday);
    StopWatch sw = new StopWatch();
    sw.start();
    this.fileUtil.uploadToHDFS(yesterday);
    sw.stop();
    LOGGER.info("上传到hdfs结束, 耗时: {} ms", sw.getTotalTimeMillis());
}
 
Example 13
Project: telegram-bot   File: FanfouTask.java   View source code 5 votes vote down vote up
@Scheduled(cron = "0 5 8 * * *")
public void daily() {
    long start = System.currentTimeMillis();
    log.info("每日精选启动...");

    try {
        String date = DateFormatUtils.format(new Date(), pattern);
        fanfouHandler.sendContent(dailyChatId, AppUtils.getFanFouDailyByDate(date));
    } catch (Exception e) {
        log.info(e.getMessage());
        appUtils.sendServerChan(e.getMessage(), ExceptionUtils.getStackTrace(e));
    }

    log.info("每日精选完成,耗时:{} ms", System.currentTimeMillis() - start);
}
 
Example 14
Project: Learning-Spring-Boot-2.0-Second-Edition   File: CommentSimulator.java   View source code 5 votes vote down vote up
@Scheduled(fixedRate = 100)
public void simulateActivity() {
	repository
		.findAll()
		.map(image -> {
			Comment comment = new Comment();
			comment.setImageId(image.getId());
			comment.setComment(
				"Comment #" + counter.getAndIncrement());
			return Mono.just(comment);
		})
		.map(commentController::addComment)
		.subscribe();
}
 
Example 15
Project: Spring-Security-Third-Edition   File: JavaConfig.java   View source code 5 votes vote down vote up
@Scheduled(fixedRate = 600_000)
public void tokenRepositoryCleaner(){
    Thread trct = new Thread(
            new JpaTokenRepositoryCleaner(
                    rememberMeTokenRepository,
                    100_000L));
    trct.start();
}
 
Example 16
Project: Learning-Spring-Boot-2.0-Second-Edition   File: CommentSimulator.java   View source code 5 votes vote down vote up
@Scheduled(fixedRate = 100)
public void simulateActivity() {
	repository
		.findAll()
		.map(image -> {
			Comment comment = new Comment();
			comment.setImageId(image.getId());
			comment.setComment(
				"Comment #" + counter.getAndIncrement());
			return Mono.just(comment);
		})
		.map(commentController::addComment)
		.subscribe();
}
 
Example 17
Project: artemis-disruptor-miaosha   File: ResponseCacheImpl.java   View source code 5 votes vote down vote up
/**
 * 定时清理缓存, 5分钟
 */
@Scheduled(fixedDelay = 1000 * 60L * 5)
public void flush() {

  Long now = System.currentTimeMillis();

  RESPONSE_MAP.keySet().stream()
      .filter(s -> RESPONSE_MAP.get(s).getValue1() < now)
      .forEach(RESPONSE_MAP::remove);

}
 
Example 18
Project: Microservices-with-JHipster-and-Spring-Boot   File: UserService.java   View source code 5 votes vote down vote up
/**
 * Not activated users should be automatically deleted after 3 days.
 * <p>
 * This is scheduled to get fired everyday, at 01:00 (am).
 * </p>
 */
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
    ZonedDateTime now = ZonedDateTime.now();
    List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3));
    for (User user : users) {
        log.debug("Deleting not activated user {}", user.getLogin());
        userRepository.delete(user);
        userSearchRepository.delete(user);
    }
}
 
Example 19
Project: rebazer   File: BitbucketService.java   View source code 5 votes vote down vote up
@Scheduled( fixedDelay = 60 * 1000 )
public void pollBitbucket() {
	for ( final Repository repo : config.getRepos() ) {
		log.debug( "Processing {}.", repo );
		for ( final PullRequest pr : getAllPullRequests( repo ) ) {
			handlePR( repo, pr );
		}
	}
}
 
Example 20
Project: jhipster-microservices-example   File: UserService.java   View source code 5 votes vote down vote up
/**
 * Not activated users should be automatically deleted after 3 days.
 * <p>
 * This is scheduled to get fired everyday, at 01:00 (am).
 * </p>
 */
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
    List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS));
    for (User user : users) {
        log.debug("Deleting not activated user {}", user.getLogin());
        userRepository.delete(user);
        userSearchRepository.delete(user);
    }
}
 
Example 21
Project: Spring-Security-Third-Edition   File: JavaConfig.java   View source code 5 votes vote down vote up
@Scheduled(fixedRate = 600_000)
public void tokenRepositoryCleaner(){
    Thread trct = new Thread(
            new JpaTokenRepositoryCleaner(
                    rememberMeTokenRepository,
                    100_000L));
    trct.start();
}
 
Example 22
Project: AngularAndSpring   File: ScheduledTask.java   View source code 5 votes vote down vote up
@Scheduled(fixedRate = 60000,initialDelay=33000)
	public void insertBitstampQuoteXRPUSD() throws InterruptedException {
		Date start = new Date();
		WebClient wc = buildWebClient(URLBS);
		try {
			operations.insert(wc.get().uri("/v2/ticker/xrpusd/").accept(MediaType.APPLICATION_JSON).exchange()
					.flatMap(response -> response.bodyToMono(QuoteBs.class)).map(res -> {res.setPair("xrpusd"); log.info(res.toString()); return res;})).then().block(Duration.ofSeconds(3));
			log.info("BitstampQuote Xrp Usd " + dateFormat.format(new Date()) + " " + (new Date().getTime()-start.getTime()) + "ms");
		} catch (Exception e) {
//			log.error("Bitstamp insert error", e);
			log.error("Bitstamp Xrp insert error Usd "+ dateFormat.format(new Date()));
		}
	}
 
Example 23
Project: patient-portal   File: UserService.java   View source code 5 votes vote down vote up
/**
 * Persistent Token are used for providing automatic authentication, they should be automatically deleted after
 * 30 days.
 * <p>
 * This is scheduled to get fired everyday, at midnight.
 */
@Scheduled(cron = "0 0 0 * * ?")
public void removeOldPersistentTokens() {
    LocalDate now = LocalDate.now();
    persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1)).forEach(token -> {
        log.debug("Deleting token {}", token.getSeries());
        User user = token.getUser();
        user.getPersistentTokens().remove(token);
        persistentTokenRepository.delete(token);
    });
}
 
Example 24
Project: sdudoc   File: TaskManager.java   View source code 5 votes vote down vote up
/**
 * 每天0点的时候,执行一遍日志删除工作,将30天之前的日志删除
 */
@Scheduled(cron = "0 0 0 * * ? ")
public void deleteLogs() {
	if (log.isInfoEnabled()) {
		log.info("执行删除日志任务");
	}
	logService.deleteLogDaysAgo(30);
}
 
Example 25
Project: fake-smtp-server   File: EmailRetentionTimer.java   View source code 5 votes vote down vote up
@Scheduled(fixedDelay = 300000, initialDelay = 500)
public void deleteOutdatedMails(){
    FakeSmtpConfigurationProperties.Persistence persistence = fakeSmtpConfigurationProperties.getPersistence();
    if(isDataRetentionConfigured(persistence)){
        int maxNumber = persistence.getMaxNumberEmails();
        int count = emailRepository.deleteEmailsExceedingDateRetentionLimit(maxNumber);
        logger.info("Deleted {} emails which exceeded the maximum number {} of emails to be stored", count, maxNumber);
    }
}
 
Example 26
Project: Code4Health-Platform   File: UserService.java   View source code 5 votes vote down vote up
/**
 * Not activated users should be automatically deleted after 3 days.
 * <p>
 * This is scheduled to get fired everyday, at 01:00 (am).
 * </p>
 */
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
    ZonedDateTime now = ZonedDateTime.now();
    List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3));
    for (User user : users) {
        log.debug("Deleting not activated user {}", user.getLogin());
        userRepository.delete(user);
        userSearchRepository.delete(user);
    }
}
 
Example 27
Project: mensa-api   File: LabelUpdater.java   View source code 5 votes vote down vote up
@Scheduled(cron = "${update.label.cron}")
public void update() {
    log.info("Starting label update");
    List<Label> labels = scraper.scrape();
    labels.forEach(label -> label.setId(UUID.randomUUID().toString()));
    if (!labels.isEmpty()) {
        List<Label> oldLabels = repo.findAll();
        log.info("Replacing {} old labels with {} new ones", oldLabels.size(), labels.size());
        repo.delete(oldLabels);
        repo.save(labels);
        log.info("Finished label update");
    } else {
        log.info("No labels found");
    }
}
 
Example 28
Project: qualitoast   File: UserService.java   View source code 5 votes vote down vote up
/**
 * Persistent Token are used for providing automatic authentication, they should be automatically deleted after
 * 30 days.
 * <p>
 * This is scheduled to get fired everyday, at midnight.
 */
@Scheduled(cron = "0 0 0 * * ?")
public void removeOldPersistentTokens() {
    LocalDate now = LocalDate.now();
    persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1)).forEach(token -> {
        log.debug("Deleting token {}", token.getSeries());
        User user = token.getUser();
        user.getPersistentTokens().remove(token);
        persistentTokenRepository.delete(token);
    });
}
 
Example 29
Project: AngularAndSpring   File: ScheduledTask.java   View source code 5 votes vote down vote up
@Scheduled(fixedRate = 60000,initialDelay=42000)
	public void insertBitfinexQuoteLTCUSD() throws InterruptedException {
		Date start = new Date();
		WebClient wc = buildWebClient(URLBF);		
		try {
			operations.insert(wc.get().uri("/v1/pubticker/ltcusd").accept(MediaType.APPLICATION_JSON).exchange()
					.flatMap(response -> response.bodyToMono(QuoteBf.class)).map(res -> {res.setPair("ltcusd"); log.info(res.toString()); return res;})).then().block(Duration.ofSeconds(3));
			log.info("BitfinexQuote Ltc Usd " + dateFormat.format(new Date()) + " " + (new Date().getTime()-start.getTime()) + "ms");
		} catch (Exception e) {
//			log.error("Bitstamp insert error", e);
			log.error("Bitfinex Ltc insert error Usd "+ dateFormat.format(new Date()));
		}
	}
 
Example 30
Project: cas-5.1.0   File: InMemoryThrottledSubmissionCleaner.java   View source code 5 votes vote down vote up
/**
 * Kicks off the job that attempts to clean the throttling submission record history.
 */
@Override
@Scheduled(initialDelayString = "${cas.authn.throttle.startDelay:PT10S}",
           fixedDelayString = "${cas.authn.throttle.repeatInterval:PT15S}")
public void run() {
    this.throttlingAdapter.decrement();
}
 
Example 31
Project: OperatieBRP   File: AdmhnProducerVoorLeveringScheduler.java   View source code 5 votes vote down vote up
/**
 * herlaad.
 */
@Scheduled(fixedDelayString = "${brp.levering.admhndpublicatie.delay:500}")
public void herlaad() {
    LOGGER.trace("start lever batch administratieve handelingen voor levering");
    admhndProducerVoorLeveringService.produceerHandelingenVoorLevering();
    LOGGER.trace("einde lever batch administratieve handelingen voor levering");
}
 
Example 32
Project: spring-boot-websocket-client   File: TimeSender.java   View source code 5 votes vote down vote up
@Scheduled(fixedRate = 5000)
public void run() {
    String time = LocalTime.now().format(TIME_FORMAT);

    log.info("Time broadcast: {}", time);
    broker.convertAndSend("/topic/greetings", new Greeting("Current time is " + time));
}
 
Example 33
Project: playground-scenario-generator   File: OnlyOneInAllScenarioRunner.java   View source code 5 votes vote down vote up
@Scheduled(fixedRate = SCENARIO_CHECK_INTERVAL)
public void checkAndReleaseScenariosOnTime() {

    for(Map.Entry<String, ScenarioWrapper> entry: runningScenariosMap.entrySet()) {
        String agentName = entry.getKey();
        ScenarioWrapper scw = entry.getValue();
        if (scw.getRemainingSeconds() <= 0) {
            scenarioService.disableScenario(agentName, scw.getScenario().getId());
            runningScenariosMap.remove(agentName);
            log.info("Scenario '" + scw.getScenario().getName() + "' is finished. " + scw.toString());
        }
    }
}
 
Example 34
Project: Ins_fb_pictureSpider_WEB   File: TimeSchedulerUtil.java   View source code 5 votes vote down vote up
@Scheduled(cron="0 0/1 * * * ?")
public void instagramTimeScheduler() {
    logger.info("正在连接Instagram获取最新Feed 。。。");
    GemInsPicture gemInsPicture = new GemInsPicture();
    gemInsPicture.flushInstagram();
    logger.info("断开连接Instagram 。。。");
}
 
Example 35
Project: fiery   File: SQLStatistic.java   View source code 5 votes vote down vote up
@Scheduled(fixedRate = 30 * 1000)
public boolean DelOutTimeSqlLog() {
    if (_sqlMap.size() > 0) {
        Map<String, ArrayList<Integer>> delSqlMap = new Hashtable<>();
        for (Map.Entry<String, Map<Long, SqlStatisticStruct>> ent : _sqlMap.entrySet()) {
            ArrayList<Long> delList = new ArrayList<>();
            if (ent.getValue().size() > 0) {
                for (Map.Entry<Long, SqlStatisticStruct> hourent : ent.getValue().entrySet()) {
                    if (hourent.getKey() >= DateTimeHelper.getCurrentTime() - fieryConfig.getKeepdataday() * 86400) {
                        continue;
                    }
                    delList.add(hourent.getKey());
                    //_sqlMap.get(ent.getKey()).remove(hourent.getKey());
                    //log.info("del out time sql log:" + ent.getKey() + ",log create_time:" + DateTimeHelper.TimeStamp2Date(hourent.getKey().toString(), "yyyy-MM-dd HH:mm:ss"));
                }
            }
            /*if (_sqlMap.get(ent.getKey()).size() == 0) {
                    _sqlMap.remove(ent.getKey());
            }*/
        }
        for (Map.Entry<String, ArrayList<Integer>> sqlent : delSqlMap.entrySet()) {
            for (Integer key : sqlent.getValue()) {
                _sqlMap.get(sqlent.getKey()).remove(key);
                log.info("del out time sql log:" + sqlent.getKey() + ",log create_time:" + DateTimeHelper
                        .TimeStamp2Date(key.toString(), "yyyy-MM-dd HH:mm:ss"));
            }
            if (_sqlMap.get(sqlent.getKey()).size() == 0) {
                _sqlMap.remove(sqlent.getKey());
            }
        }
    }
    return true;
}
 
Example 36
Project: dashboard1b   File: KafkaProducer.java   View source code 5 votes vote down vote up
@Scheduled(fixedDelay = 7000)
public void sendNewApoyo() {
    String comentarioJSON = "";
    comentario = randomGenerator.newComentario();
    comentario.setTexto("");

    try {
        comentarioJSON = mapper.writeValueAsString(comentario);
        send("apoyos", comentarioJSON);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}
 
Example 37
Project: nixmash-blog   File: GithubJobRunner.java   View source code 5 votes vote down vote up
@Scheduled(fixedRateString = "${github.job.fixed.delay.seconds:60}000")
public void runGithubJob() {

    SimpleDateFormat format = new SimpleDateFormat("M-dd-yy hh:mm:ss");
    String startDateTime = format.format(new Date());

    JobParameters jobParameters =
            new JobParametersBuilder()
                    .addLong("time", System.currentTimeMillis()).toJobParameters();

    try {
        logger.info("");
        logger.info("STARTING GITHUB BATCH JOB : " + startDateTime);
        JobExecution execution = jobLauncher.run(githubJob, jobParameters);
        logger.info("JOB STATUS  : " + execution.getStatus());
    } catch (Exception e) {
        e.printStackTrace();
        logger.info("JOB FAILED!!!");
    }

}
 
Example 38
Project: flow-platform   File: CmdDispatchServiceImpl.java   View source code 5 votes vote down vote up
@Override
@Transactional(propagation = Propagation.NEVER)
@Scheduled(fixedDelay = 300 * 1000)
public void checkTimeoutTask() {
    if (!taskConfig.isEnableCmdExecTimeoutTask()) {
        return;
    }
    LOGGER.traceMarker("checkTimeoutTask", "start");

    // find all running status cmd
    List<Cmd> workingCmdList = cmdService.listWorkingCmd(null);

    for (Cmd cmd : workingCmdList) {
        if (cmd.getType() != CmdType.RUN_SHELL || !cmd.isCurrent()) {
            continue;
        }

        if (DateUtil.isTimeOut(cmd.getCreatedDate(), ZonedDateTime.now(), cmd.getTimeout())) {
            try {
                Cmd killCmd = cmdService.create(new CmdInfo(cmd.getAgentPath(), CmdType.KILL, null));
                dispatch(killCmd);
                LOGGER.traceMarker("checkTimeoutTask", "Send KILL for timeout cmd %s", cmd);

                CmdStatusItem statusItem = new CmdStatusItem(cmd.getId(), CmdStatus.TIMEOUT_KILL, null, true, true);
                cmdService.updateStatus(statusItem, false);
            } catch (Throwable e) {
                LOGGER.warn(e.getMessage());
            }
        }
    }

    LOGGER.traceMarker("checkTimeoutTask", "end");
}
 
Example 39
Project: mensa-api   File: AllergenUpdater.java   View source code 5 votes vote down vote up
@Scheduled(cron = "${update.allergen.cron}")
public void update() {
    log.info("Starting allergen update");
    List<Allergen> allergens = scraper.scrape();
    if (!allergens.isEmpty()) {
        List<Allergen> oldAllergens = repo.findAll();
        log.info("Replacing {} old allergens with {} new ones", oldAllergens.size(), allergens.size());
        repo.delete(oldAllergens);
        repo.save(allergens);
        log.info("Finished allergen update");
    } else {
        log.info("No allergens found");
    }
}
 
Example 40
Project: sentry   File: UserService.java   View source code 5 votes vote down vote up
/**
 * Persistent Token are used for providing automatic authentication, they should be automatically deleted after
 * 30 days.
 * <p>
 * This is scheduled to get fired everyday, at midnight.
 * </p>
 */
@Scheduled(cron = "0 0 0 * * ?")
public void removeOldPersistentTokens() {
    LocalDate now = LocalDate.now();
    persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1)).forEach(token -> {
        log.debug("Deleting token {}", token.getSeries());
        persistentTokenRepository.delete(token);
    });
}