當前位置: 首頁>>代碼示例>>Java>>正文


Java Scheduled類代碼示例

本文整理匯總了Java中org.springframework.scheduling.annotation.Scheduled的典型用法代碼示例。如果您正苦於以下問題:Java Scheduled類的具體用法?Java Scheduled怎麽用?Java Scheduled使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Scheduled類屬於org.springframework.scheduling.annotation包,在下文中一共展示了Scheduled類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: indexedData

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:thinksky-sourcecode,項目名稱:microservices-prototype,代碼行數:24,代碼來源:DataService.java

示例2: execute

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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");
}
 
開發者ID:zhaojunfei,項目名稱:lemon,代碼行數:18,代碼來源:TaskTimeoutJob.java

示例3: purgeOldNotifications

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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);
}
 
開發者ID:mshaw323,項目名稱:stdds-monitor,代碼行數:21,代碼來源:DataScheduler.java

示例4: sessionTimeoutTask

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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");
}
 
開發者ID:FlowCI,項目名稱:flow-platform,代碼行數:25,代碼來源:AgentServiceImpl.java

示例5: insertCoinbaseQuote

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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()));
		}
	}
 
開發者ID:Angular2Guy,項目名稱:AngularAndSpring,代碼行數:19,代碼來源:ScheduledTask.java

示例6: execute

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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()));
		}
	});
}
 
開發者ID:7upcat,項目名稱:agile-wroking-backend,代碼行數:21,代碼來源:SendNotifyMessageJob.java

示例7: buildJwks

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
/**
 * 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());
        }
    }

}
 
開發者ID:trajano,項目名稱:app-ms,代碼行數:21,代碼來源:CachedDataProvider.java

示例8: process

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
/**
 * 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.");
        }
    }
}
 
開發者ID:sscholl,項目名稱:biblebot,代碼行數:22,代碼來源:PostService.java

示例9: storeUserCountMetrics

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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())
    );
}
 
開發者ID:quanticc,項目名稱:sentry,代碼行數:18,代碼來源:UserCountService.java

示例10: autoCancel

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
/**
 */
@Scheduled(fixedRate = 10000)
public void autoCancel() {
	// 獲取過期的資源
	final List<ProuctTcc> tccs = productTccRepositorie.expireReservation(2);
	tccs.forEach(tcc -> {
		cancel(tcc.getId());
	});
}
 
開發者ID:zhaoqilong3031,項目名稱:spring-cloud-samples,代碼行數:11,代碼來源:ProductService.java

示例11: killHLSStreams

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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) {
                            }
                        }
                    }
                }
            }
        }

    }
}
 
開發者ID:segator,項目名稱:proxylive,代碼行數:28,代碼來源:ProcessorTasks.java

示例12: upload

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
/**
 * 上傳到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());
}
 
開發者ID:JThink,項目名稱:SkyEye,代碼行數:14,代碼來源:UploadTask.java

示例13: daily

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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);
}
 
開發者ID:junbaor,項目名稱:telegram-bot,代碼行數:16,代碼來源:FanfouTask.java

示例14: simulateActivity

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@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();
}
 
開發者ID:PacktPublishing,項目名稱:Learning-Spring-Boot-2.0-Second-Edition,代碼行數:15,代碼來源:CommentSimulator.java

示例15: tokenRepositoryCleaner

import org.springframework.scheduling.annotation.Scheduled; //導入依賴的package包/類
@Scheduled(fixedRate = 600_000)
public void tokenRepositoryCleaner(){
    Thread trct = new Thread(
            new JpaTokenRepositoryCleaner(
                    rememberMeTokenRepository,
                    100_000L));
    trct.start();
}
 
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:9,代碼來源:JavaConfig.java


注:本文中的org.springframework.scheduling.annotation.Scheduled類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。