Java 类org.springframework.scheduling.annotation.Scheduled 实例源码

项目:sentry    文件:UserCountService.java   
@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())
    );
}
项目:microservices-prototype    文件:DataService.java   
@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);
    }
}
项目:lemon    文件:TaskTimeoutJob.java   
@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");
}
项目:stdds-monitor    文件:DataScheduler.java   
@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);
}
项目:flow-platform    文件:AgentServiceImpl.java   
@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");
}
项目:AngularAndSpring    文件:ScheduledTask.java   
@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()));
        }
    }
项目:agile-wroking-backend    文件:SendNotifyMessageJob.java   
@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()));
        }
    });
}
项目:app-ms    文件:CachedDataProvider.java   
/**
 * 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());
        }
    }

}
项目:biblebot    文件:PostService.java   
/**
 * 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.");
        }
    }
}
项目:spring-cloud-samples    文件:ProductService.java   
/**
 */
@Scheduled(fixedRate = 10000)
public void autoCancel() {
    // 获取过期的资源
    final List<ProuctTcc> tccs = productTccRepositorie.expireReservation(2);
    tccs.forEach(tcc -> {
        cancel(tcc.getId());
    });
}
项目:proxylive    文件:ProcessorTasks.java   
@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) {
                            }
                        }
                    }
                }
            }
        }

    }
}
项目:SkyEye    文件:UploadTask.java   
/**
 * 上传到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());
}
项目:telegram-bot    文件:FanfouTask.java   
@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);
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:CommentSimulator.java   
@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();
}
项目:Spring-Security-Third-Edition    文件:JavaConfig.java   
@Scheduled(fixedRate = 600_000)
public void tokenRepositoryCleaner(){
    Thread trct = new Thread(
            new JpaTokenRepositoryCleaner(
                    rememberMeTokenRepository,
                    100_000L));
    trct.start();
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:CommentSimulator.java   
@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();
}
项目:artemis-disruptor-miaosha    文件:ResponseCacheImpl.java   
/**
 * 定时清理缓存, 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);

}
项目:Microservices-with-JHipster-and-Spring-Boot    文件:UserService.java   
/**
 * 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);
    }
}
项目:rebazer    文件:BitbucketService.java   
@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 );
        }
    }
}
项目:jhipster-microservices-example    文件:UserService.java   
/**
 * 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);
    }
}
项目:Spring-Security-Third-Edition    文件:JavaConfig.java   
@Scheduled(fixedRate = 600_000)
public void tokenRepositoryCleaner(){
    Thread trct = new Thread(
            new JpaTokenRepositoryCleaner(
                    rememberMeTokenRepository,
                    100_000L));
    trct.start();
}
项目:AngularAndSpring    文件:ScheduledTask.java   
@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()));
        }
    }
项目:patient-portal    文件:UserService.java   
/**
 * 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);
    });
}
项目:sdudoc    文件:TaskManager.java   
/**
 * 每天0点的时候,执行一遍日志删除工作,将30天之前的日志删除
 */
@Scheduled(cron = "0 0 0 * * ? ")
public void deleteLogs() {
    if (log.isInfoEnabled()) {
        log.info("执行删除日志任务");
    }
    logService.deleteLogDaysAgo(30);
}
项目:fake-smtp-server    文件:EmailRetentionTimer.java   
@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);
    }
}
项目:Code4Health-Platform    文件:UserService.java   
/**
 * 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);
    }
}
项目:mensa-api    文件:LabelUpdater.java   
@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");
    }
}
项目:qualitoast    文件:UserService.java   
/**
 * 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);
    });
}
项目:AngularAndSpring    文件:ScheduledTask.java   
@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()));
        }
    }
项目:cas-5.1.0    文件:InMemoryThrottledSubmissionCleaner.java   
/**
 * 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();
}
项目:OperatieBRP    文件:AdmhnProducerVoorLeveringScheduler.java   
/**
 * 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");
}
项目:spring-boot-websocket-client    文件:TimeSender.java   
@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));
}
项目:playground-scenario-generator    文件:OnlyOneInAllScenarioRunner.java   
@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());
        }
    }
}
项目:Ins_fb_pictureSpider_WEB    文件:TimeSchedulerUtil.java   
@Scheduled(cron="0 0/1 * * * ?")
public void instagramTimeScheduler() {
    logger.info("正在连接Instagram获取最新Feed 。。。");
    GemInsPicture gemInsPicture = new GemInsPicture();
    gemInsPicture.flushInstagram();
    logger.info("断开连接Instagram 。。。");
}
项目:fiery    文件:SQLStatistic.java   
@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;
}
项目:dashboard1b    文件:KafkaProducer.java   
@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();
    }
}
项目:nixmash-blog    文件:GithubJobRunner.java   
@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!!!");
    }

}
项目:flow-platform    文件:CmdDispatchServiceImpl.java   
@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");
}
项目:mensa-api    文件:AllergenUpdater.java   
@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");
    }
}
项目:sentry    文件:UserService.java   
/**
 * 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);
    });
}