org.springframework.scheduling.annotation.Scheduled Java Examples

The following examples show how to use org.springframework.scheduling.annotation.Scheduled. 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: StartDayService.java    From smartapp-sdk-java with Apache License 2.0 6 votes vote down vote up
@Scheduled(cron = "0 0 7 * * *")
public void goodMorning() {
    DevicesApi devicesApi = apiClient.buildClient(DevicesApi.class);
    log.info("waking up");
    installedAppContextStore.get().forEach(context -> {
        log.info("context = " + context);
        ConfigEntries selectedSwitches = context.getInstalledApp().getConfig().get("selectedSwitches");
        for (ConfigEntry entry : selectedSwitches) {
            DeviceConfig deviceConfig = entry.getDeviceConfig();
            if (deviceConfig != null) {
                String auth = context.getAuth();
                devicesApi.executeDeviceCommands(auth, deviceConfig.getDeviceId(), DEVICE_ON);
            }
        }
    });
}
 
Example #2
Source File: OperationEventJobsHandler.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
@Scheduled(cron="*/30 * * * * ?")
public void extractOutstandingOperationEvents(){
    if(log.isInfoEnabled()){
        log.info("scheduled execution start...");
    }
    
    try{
        operationEventsProcessor.execute();
    }catch(Exception e){
        log.error("operation event processing errors", e);
    }
    
    if(log.isInfoEnabled()){
        log.info("scheduled execution end...");
    }
}
 
Example #3
Source File: OrderUpdateJob.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
@Scheduled(fixedRate = 60*1000)
public void autoCancelOrder(){
    logger.info("start autoCancelOrder...");
    List<ExchangeCoin> coinList = coinService.findAllEnabled();
    coinList.forEach(coin->{
        if(coin.getMaxTradingTime() > 0){
            List<ExchangeOrder> orders =  orderService.findOvertimeOrder(coin.getSymbol(),coin.getMaxTradingTime());
            orders.forEach(order -> {
                // 发送消息至Exchange系统
                kafkaTemplate.send("exchange-order-cancel", JSON.toJSONString(order));
                logger.info("orderId:"+order.getOrderId()+",time:"+order.getTime());
            });
        }
    });
    logger.info("end autoCancelOrder...");
}
 
Example #4
Source File: CleanJobTask.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Scheduled(cron= "0 0 1 1 * ?")
   public void task() {
	if(UKDataContext.getContext()!=null && UKDataContext.needRunTask()){
		Page<JobDetail> pageList = null;
		do {
			pageList = jobDetailRepository.findAll(new Specification<JobDetail>(){
				@Override
				public Predicate toPredicate(Root<JobDetail> root, CriteriaQuery<?> query,
						CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<Predicate>();  

					list.add(cb.equal(root.get("tasktype").as(String.class), UKDataContext.TaskType.RECOVERY.toString()));
					list.add(cb.equal(root.get("taskstatus").as(String.class), UKDataContext.TaskStatusType.NORMAL.getType()));
					//3天前
					list.add(cb.lessThanOrEqualTo(root.get("createtime").as(Date.class), UKTools.getLastDay(3)));
					Predicate[] p = new Predicate[list.size()];  
					return cb.and(list.toArray(p));   
				}}, new PageRequest(0, 1000, Sort.Direction.ASC, new String[] { "createtime" }));
			if(pageList.getContent().size()  > 0 ) {
				jobDetailRepository.delete(pageList.getContent());
			}
		}while(pageList.getContent().size() > 0 );
	}
}
 
Example #5
Source File: SyncClientsHeartbeatTask.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
@Scheduled(initialDelayString = "${session.server.syncHeartbeat.fixedDelay}", fixedDelayString = "${session.server.syncHeartbeat.fixedDelay}")
public void syncCounte() {
    long countSub = sessionInterests.count();
    long countPub = sessionDataStore.count();
    long countSubW = sessionWatchers.count();

    int channelCount = 0;
    Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort());
    if (sessionServer != null) {
        channelCount = sessionServer.getChannelCount();
    }

    CONSOLE_COUNT_LOGGER.info(
        "Subscriber count: {}, Publisher count: {}, Watcher count: {}, Connection count: {}",
        countSub, countPub, countSubW, channelCount);
}
 
Example #6
Source File: CountScheduledTasks.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Scheduled(cron = "0 00 2 ? * * ") //每天凌晨2:00执行

    public void syncPostViews() {
        Long startTime = System.nanoTime();
        List dtoList = new ArrayList<>();
        Set<String> keySet = stringRedisTemplate.keys("name::*");
        for (String key : keySet) {
            String views = stringRedisTemplate.opsForValue().get(key);
            String sid = key.replaceAll("name::", "");
            long lid = Long.parseLong(sid);
            long lviews = Long.parseLong(views);
            //批量更新可以用Collection<?>
            articleRepository.updateArticleViewById(lviews, lid);
            //删除key
            stringRedisTemplate.delete(key);
        }

    }
 
Example #7
Source File: SourceRequestCron.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
@Scheduled(fixedDelay = SECOND * 10)
public void syncToInternali18nManager() {
	while (!TaskSysnQueues.SendComponentTasks.isEmpty()) {
		logger.info("begin synch local component Model to VIP i18n");

		RecordModel record = TaskSysnQueues.SendComponentTasks.poll();
		if (record != null) {

			boolean result = singleComponentService.synchComponentFile2I18n(record);

			if (result) {
				singleComponentService.delSourceComponentFile(record);
				logger.info("synch component Model to VIP successfully!!!");
			} else {
				logger.error("synch component Model to VIP failure!!!");
			}

		} else {
			logger.info("no synch component!!!!!");
		}

	}

}
 
Example #8
Source File: HeartBeatService.java    From influx-proxy with Apache License 2.0 6 votes vote down vote up
@Scheduled(fixedRate = 5_000)
public void heartBeat() {
    if(proxyConfiguration.isEnable()||StringUtils.isEmpty(opsPath)){
        return;
    }
    try{
        InetUtils.HostInfo hostInfo = inetUtils.findFirstNonLoopbackHostInfo();
        restTemplate.getForObject(opsPath + "/ping?ip={1}&port={2}&managementPort={3}&hostname={4}",
                String.class,
                hostInfo.getIpAddress(),
                port,
                managementPort,
                hostInfo.getHostname());
    }catch (Throwable ignore){
        log.warn("Failed to ping {}",opsPath);
    }
}
 
Example #9
Source File: RedisClusterReplicationCheckJob.java    From cymbal with Apache License 2.0 6 votes vote down vote up
@Scheduled(cron = "${job.replication.cron}")
public void execute() {
    long startTime = System.currentTimeMillis();
    log.info("RedisClusterReplicationCheckJob started.");
    // TODO: Query with page
    List<ClusterBO> redisClusterBOs = clusterProcessService.queryAllRedisClusters();
    for (ClusterBO eachRedisClusterBO : redisClusterBOs) {
        try {
            if (AlarmLevel.LOG.equals(eachRedisClusterBO.getCluster().getAlarmLevel())) {
                log.warn("Cluster of id '{}' is sign to skip alarm, skip check.",
                        eachRedisClusterBO.getCluster().getClusterId());
                continue;
            }
            doAlarmIfNeeded(eachRedisClusterBO);
        } catch (CymbalException e) {
            log.error(String.format("RedisMasterDistributionCheckJob error of clusterId %s",
                    eachRedisClusterBO.getCluster().getClusterId()), e);
        }
    }

    log.info("RedisClusterReplicationCheckJob finished, duration time {} ms.",
            System.currentTimeMillis() - startTime);
}
 
Example #10
Source File: CouponJob.java    From dts-shop with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 每隔一个小时检查
 */
@Scheduled(fixedDelay = 60 * 60 * 1000)
public void checkCouponExpired() {
	logger.info("系统开启任务检查优惠券是否已经过期");

	List<DtsCoupon> couponList = couponService.queryExpired();
	for (DtsCoupon coupon : couponList) {
		coupon.setStatus(CouponConstant.STATUS_EXPIRED);
		couponService.updateById(coupon);
	}

	List<DtsCouponUser> couponUserList = couponUserService.queryExpired();
	for (DtsCouponUser couponUser : couponUserList) {
		couponUser.setStatus(CouponUserConstant.STATUS_EXPIRED);
		couponUserService.update(couponUser);
	}
}
 
Example #11
Source File: CinemaSocket.java    From dbys with GNU General Public License v3.0 6 votes vote down vote up
@Scheduled(cron="0 */1 * * * ?")
public void examine(){
    DELETE_P00L.clear();
    //删除断开的链接
    POOL.forEach((id,e)->{
        if(!e.session.isOpen()){
            POOL.remove(id);
        }
    });
    ROOM_POOL.forEach((id,room)->{
        if(POOL.get(room.getAuthorId())==null){
            if(room.getSockets().size()<2){
                ROOM_POOL.remove(id);
            }else {
                //新房主
                String newId = CinemaSocket.ROOM_POOL.get(id).getSockets().iterator().next();
                //转让
                if (newId != null) {
                    CinemaSocket.ROOM_POOL.get(roomId).setAuthorId(newId);
                }
            }
        }
    });
}
 
Example #12
Source File: OrderJob.java    From dts-shop with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 可评价订单商品超期
 * <p>
 * 定时检查订单商品评价情况,如果确认商品超时七天则取消可评价状态 定时时间是每天凌晨4点。
 */
@Scheduled(cron = "0 0 4 * * ?")
public void checkOrderComment() {
	logger.info("系统开启任务检查订单是否已经超期未评价");

	LocalDateTime now = LocalDateTime.now();
	List<DtsOrder> orderList = orderService.queryComment();
	for (DtsOrder order : orderList) {
		LocalDateTime confirm = order.getConfirmTime();
		LocalDateTime expired = confirm.plusDays(7);
		if (expired.isAfter(now)) {
			continue;
		}

		order.setComments((short) 0);
		orderService.updateWithOptimisticLocker(order);

		List<DtsOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());
		for (DtsOrderGoods orderGoods : orderGoodsList) {
			orderGoods.setComment(-1);
			orderGoodsService.updateById(orderGoods);
		}
	}
}
 
Example #13
Source File: OrderJob.java    From dts-shop with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 自动确认订单
 * <p>
 * 定时检查订单未确认情况,如果超时七天则自动确认订单 定时时间是每天凌晨3点。
 * <p>
 * 注意,因为是相隔一天检查,因此导致有订单是超时八天以后才设置自动确认。 这里可以进一步地配合用户订单查询时订单未确认检查,如果订单超时7天则自动确认。
 * 但是,这里可能不是非常必要。相比订单未付款检查中存在商品资源有限所以应该 早点清理未付款情况,这里八天再确认是可以的。。
 */
@Scheduled(cron = "0 0 3 * * ?")
public void checkOrderUnconfirm() {
	logger.info("系统开启任务检查订单是否已经超期自动确认收货");

	List<DtsOrder> orderList = orderService.queryUnconfirm();
	for (DtsOrder order : orderList) {
		LocalDateTime ship = order.getShipTime();
		LocalDateTime now = LocalDateTime.now();
		LocalDateTime expired = ship.plusDays(7);
		if (expired.isAfter(now)) {
			continue;
		}

		// 设置订单已取消状态
		order.setOrderStatus(OrderUtil.STATUS_AUTO_CONFIRM);
		order.setConfirmTime(now);
		if (orderService.updateWithOptimisticLocker(order) == 0) {
			logger.info("订单 ID=" + order.getId() + " 数据已经更新,放弃自动确认收货");
		} else {
			logger.info("订单 ID=" + order.getId() + " 已经超期自动确认收货");
		}
	}
}
 
Example #14
Source File: OrderJob.java    From mall with MIT License 6 votes vote down vote up
/**
 * 自动确认订单
 * <p>
 * 定时检查订单未确认情况,如果超时七天则自动确认订单
 * 定时时间是每天凌晨3点。
 * <p>
 * 注意,因为是相隔一天检查,因此导致有订单是超时八天以后才设置自动确认。
 * 这里可以进一步地配合用户订单查询时订单未确认检查,如果订单超时7天则自动确认。
 * 但是,这里可能不是非常必要。相比订单未付款检查中存在商品资源有限所以应该
 * 早点清理未付款情况,这里八天再确认是可以的。。
 */
@Scheduled(cron = "0 0 3 * * ?")
public void checkOrderUnconfirm() {
    logger.info("系统开启任务检查订单是否已经超期自动确认收货");

    List<LitemallOrder> orderList = orderService.queryUnconfirm();
    for (LitemallOrder order : orderList) {
        LocalDateTime ship = order.getShipTime();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expired = ship.plusDays(7);
        if (expired.isAfter(now)) {
            continue;
        }

        // 设置订单已取消状态
        order.setOrderStatus(OrderUtil.STATUS_AUTO_CONFIRM);
        order.setConfirmTime(now);
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            logger.info("订单 ID=" + order.getId() + " 数据已经更新,放弃自动确认收货");
        } else {
            logger.info("订单 ID=" + order.getId() + " 已经超期自动确认收货");
        }
    }
}
 
Example #15
Source File: SignJob.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
@Scheduled(cron = "0 0 0 * * ?")
@Transactional(rollbackFor = Exception.class)
public void job() {
    Sign sign = signService.fetchUnderway();
    if (sign == null){
        log.info("sign = { null }");
        return;
    }
    log.info("sign = {}" ,sign);
    memberService.resetSignIn();//赋予签到能力
    //判断今天活动是否到期
    int compare = DateUtil.compare(sign.getEndDate(), new Date());
    log.info("比较时间" );
    log.info("compare = {}" ,compare);
    if (compare != 1) {
        sign.setStatus(SignStatus.FINISH);//当前时间小于等于是结束时间 关闭签到活动
    }
}
 
Example #16
Source File: CouponJob.java    From mall with MIT License 6 votes vote down vote up
/**
 * 每隔一个小时检查
 */
@Scheduled(fixedDelay = 60 * 60 * 1000)
public void checkCouponExpired() {
    logger.info("系统开启任务检查优惠券是否已经过期");

    List<LitemallCoupon> couponList = couponService.queryExpired();
    for(LitemallCoupon coupon : couponList){
        coupon.setStatus(CouponConstant.STATUS_EXPIRED);
        couponService.updateById(coupon);
    }

    List<LitemallCouponUser> couponUserList = couponUserService.queryExpired();
    for(LitemallCouponUser couponUser : couponUserList){
        couponUser.setStatus(CouponUserConstant.STATUS_EXPIRED);
        couponUserService.update(couponUser);
    }
}
 
Example #17
Source File: MonitorService.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * scheduled task to sync Monitor Info per 5s
 * 
 * @throws ExecutionException
 * @throws InterruptedException
 */
@Scheduled(cron = "0/5 * * * * ?")
public void syncMonitorInfo() throws ExecutionException, InterruptedException {
    log.debug("begin sync chain data");
    if (!constants.isMonitorEnabled()) {
        return;
    }
    Long currentTime = System.currentTimeMillis();
    // to do add more group
    for (Map.Entry<Integer, Web3j> entry : web3jMap.entrySet()) {
        Monitor monitor = new Monitor();
        CompletableFuture<BlockNumber> blockHeightFuture =
                entry.getValue().getBlockNumber().sendAsync();
        CompletableFuture<PbftView> pbftViewFuture = entry.getValue().getPbftView().sendAsync();
        CompletableFuture<PendingTxSize> pendingTxSizeFuture =
                entry.getValue().getPendingTxSize().sendAsync();

        monitor.setBlockHeight(blockHeightFuture.get().getBlockNumber());
        monitor.setPbftView(pbftViewFuture.get().getPbftView());
        monitor.setPendingTransactionCount(pendingTxSizeFuture.get().getPendingTxSize());
        monitor.setTimestamp(currentTime);
        monitor.setGroupId(entry.getKey());
        monitorRepository.save(monitor);
        log.debug("insert success =  " + monitor.getId());
    }
}
 
Example #18
Source File: ApacheHttpClientConfig.java    From sfg-blog-posts with GNU General Public License v3.0 6 votes vote down vote up
@Bean
public Runnable idleConnectionMonitor(PoolingHttpClientConnectionManager pool) {
  return new Runnable() {
    @Override
    @Scheduled(fixedDelay = 20000)
    public void run() {
      // only if connection pool is initialised
      if (pool != null) {
        pool.closeExpiredConnections();
        pool.closeIdleConnections(IDLE_CONNECTION_WAIT_TIME, TimeUnit.MILLISECONDS);

        LOG.info("Idle connection monitor: Closing expired and idle connections");
      }
    }
  };
}
 
Example #19
Source File: ScheduleTask.java    From molicode with Apache License 2.0 5 votes vote down vote up
/**
 * 每隔半小时删除零时文件夹信息
 *
 * @throws InterruptedException
 */
@Async
@Scheduled(fixedDelay = 1800 * 1000)  //间隔半小时
public void wipeTempData() throws InterruptedException {
    LogHelper.DEFAULT.info("执行临时文件夹清理start");
    String outputFilePath = FileIoUtil.getRuntimeFilePath("code_output");
    File file = new File(outputFilePath);
    if (file.exists() && file.isDirectory()) {
        cleanTempFile(file);
    }
    LogHelper.DEFAULT.info("执行临时文件夹清理end");
}
 
Example #20
Source File: Send2GitSchedule.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
@Scheduled(fixedDelay = SECOND)
public void syncSourceToRemoteAndLocal() {

	while (!Send2GitQueue.isEmpty()) {
		SynchFile2GitReq req = Send2GitQueue.poll();
		if (req != null) {
			if(gitRemoteEnabled) {
				try {
					// copy the files to tmp repository with product and version limit
					List<File> changeFiles = copyFile2GitTempFiles(req);
					//merge to local repository
					String commitId =  mergeChanges2LocalRepoAndCommit(changeFiles, req.getProductName(), req.getVersion());
					
					// do send commit to remote git
					
					if(commitId != null) {
						
						pushChangeFile2remote();
					}
				}catch(Exception e) {
					logger.error(e.getMessage(), e);
					SynchInfoService.updateCacheToken(req.getProductName(), req.getVersion());
				}
			}else {
				SynchInfoService.updateCacheToken(req.getProductName(), req.getVersion());
			}
		}

	}

}
 
Example #21
Source File: OrderJob.java    From dts-shop with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 自动取消订单
 * <p>
 * 定时检查订单未付款情况,如果超时半个小时则自动取消订单 定时时间是每次相隔半个小时。
 * <p>
 * 注意,因为是相隔半小时检查,因此导致有订单是超时一个小时以后才设置取消状态。 TODO
 * 这里可以进一步地配合用户订单查询时订单未付款检查,如果订单超时半小时则取消。
 */
@Scheduled(fixedDelay = 30 * 60 * 1000)
@Transactional
public void checkOrderUnpaid() {
	logger.info("系统开启任务检查订单是否已经超期自动取消订单");

	List<DtsOrder> orderList = orderService.queryUnpaid();
	for (DtsOrder order : orderList) {
		LocalDateTime add = order.getAddTime();
		LocalDateTime now = LocalDateTime.now();
		LocalDateTime expired = add.plusMinutes(30);
		if (expired.isAfter(now)) {
			continue;
		}

		// 设置订单已取消状态
		order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
		order.setEndTime(LocalDateTime.now());
		if (orderService.updateWithOptimisticLocker(order) == 0) {
			throw new RuntimeException("更新数据已失效");
		}

		// 商品货品数量增加
		Integer orderId = order.getId();
		List<DtsOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
		for (DtsOrderGoods orderGoods : orderGoodsList) {
			Integer productId = orderGoods.getProductId();
			Short number = orderGoods.getNumber();
			if (productService.addStock(productId, number) == 0) {
				throw new RuntimeException("商品货品库存增加失败");
			}
		}
		logger.info("订单 ID=" + order.getId() + " 已经超期自动取消订单");
	}
}
 
Example #22
Source File: UserService.java    From alchemy with Apache License 2.0 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).
 */
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
    userRepository
        .findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
        .forEach(user -> {
            log.debug("Deleting not activated user {}", user.getLogin());
            userRepository.delete(user);
            this.clearUserCaches(user);
        });
}
 
Example #23
Source File: KLineGeneratorJob.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 每小时运行
 */
@Scheduled(cron = "0 0 * * * *")
public void handleHourKLine(){
    processorFactory.getProcessorMap().forEach((symbol,processor)-> {
        Calendar calendar = Calendar.getInstance();
        log.info("小时K线:{}",calendar.getTime());
        //将秒、微秒字段置为0
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long time = calendar.getTimeInMillis();

        processor.generateKLine(1, Calendar.HOUR_OF_DAY, time);
    });
}
 
Example #24
Source File: ExchangePushJob.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@Scheduled(fixedRate = 500)
public void pushPlate(){
    Iterator<Map.Entry<String,List<TradePlate>>> entryIterator = plateQueue.entrySet().iterator();
    while (entryIterator.hasNext()){
        Map.Entry<String,List<TradePlate>> entry =  entryIterator.next();
        String symbol = entry.getKey();
        List<TradePlate> plates = entry.getValue();
        if(plates.size() > 0){
            boolean hasPushAskPlate = false;
            boolean hasPushBidPlate = false;
            synchronized (plates) {
                for(TradePlate plate:plates) {
                    if(plate.getDirection() == ExchangeOrderDirection.BUY && !hasPushBidPlate) {
                        hasPushBidPlate = true;
                    }
                    else if(plate.getDirection() == ExchangeOrderDirection.SELL && !hasPushAskPlate){
                        hasPushAskPlate = true;
                    }
                    else {
                        continue;
                    }
                    //websocket推送盘口信息
                    messagingTemplate.convertAndSend("/topic/market/trade-plate/" + symbol, plate.toJSON(24));
                    //websocket推送深度信息
                    messagingTemplate.convertAndSend("/topic/market/trade-depth/" + symbol, plate.toJSON());
                    //netty推送
                    nettyHandler.handlePlate(symbol, plate);
                }
                plates.clear();
            }
        }
    }
}
 
Example #25
Source File: CoinExchangeRate.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 每小时同步一次价格
 *
 * @throws UnirestException
 */
@Scheduled(cron = "0 0 * * * *")
public void syncPrice() throws UnirestException {
    String url = "https://forex.1forge.com/1.0.2/quotes";
    HttpResponse<JsonNode> resp = Unirest.get(url)
            .queryString("pairs", "USDCNH,USDJPY,USDHKD,SGDCNH")
            .queryString("api_key", "y4lmqQRykolHFp3VkzjYp2XZfgCdo8Tv")
            .asJson();
    log.info("forex result:{}", resp.getBody());
    JSONArray result = JSON.parseArray(resp.getBody().toString());
    result.forEach(json -> {
        JSONObject obj = (JSONObject) json;
        if ("USDCNH".equals(obj.getString("symbol"))) {
            setUsdCnyRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
            log.info(obj.toString());
        } else if ("USDJPY".equals(obj.getString("symbol"))) {
            setUsdJpyRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
            log.info(obj.toString());
        } else if ("USDHKD".equals(obj.getString("symbol"))) {
            setUsdHkdRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
            log.info(obj.toString());
        } else if("SGDCNH".equals(obj.getString("symbol"))){
            setSgdCnyRate(new BigDecimal(obj.getDouble("price")).setScale(2,RoundingMode.DOWN));
            log.info(obj.toString());
        }
    });
}
 
Example #26
Source File: UserService.java    From flair-engine with Apache License 2.0 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).
 */
@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);
    }
}
 
Example #27
Source File: DailyWorkloadStatisticTask.java    From HIS with Apache License 2.0 5 votes vote down vote up
/**
 * 描述:每天00:05:00开始执行,统计前一天所有员工、科室工作量并插入数据库
 * <p>author: ma
 */
@Scheduled(cron = "0 5 0 ? * *")
private void dailyWorkloadStatistic(){
    LOGGER.info("开始每日统计:");
    //获取当前时间前一天
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.DAY_OF_MONTH, -1);
    LOGGER.info("插入数据:" + smsWorkloadService.statistic(calendar.getTime()));
    LOGGER.info("统计结束---------------");
}
 
Example #28
Source File: GoBackTask.java    From permission with Apache License 2.0 5 votes vote down vote up
/**
 * CronTrigger配置完整格式为: [秒][分][小时][日][月][周][年]
 * (cron = "0/2 * * * * ?") //每两秒
 *
 * 每3小时重置mysql和redis
 *
 */
@Scheduled(cron = "0 0 0/3 * * ?")
public void goBack() {
    // 清空缓存
    flushRedis();
    // 重置mysql
    resetDb();
}
 
Example #29
Source File: UserService.java    From cubeai with Apache License 2.0 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).
 */
@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);
        cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).evict(user.getLogin());
        cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE).evict(user.getEmail());
    }
}
 
Example #30
Source File: SourceToLatestCron.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
@Scheduled(cron = "0 0/1 * * * ?")
public void syncBkSourceToRemote() {

	    	List<String> keys;
	    	try {
	    		try {
	    		keys = TranslationCache3.getKeys(CacheName.MTSOURCE, ComponentMessagesDTO.class);
	    		}catch(NullPointerException e) {
	    			keys = null;
	    		}
	    		if(keys != null) {
	    			for(String key: keys) {
		    			ComponentMessagesDTO d = TranslationCache3.getCachedObject(CacheName.MTSOURCE, key, ComponentMessagesDTO.class);
		    			if(d != null && !StringUtils.isEmpty(d.getMessages()) && key.contains(ConstantsKeys.LATEST + ConstantsChar.UNDERLINE + ConstantsKeys.MT)) {
		    				LOGGER.info("Sync data to latest.json for " + key);
		    				productService.updateTranslation(d);
		    				TranslationCache3.deleteCachedObject(CacheName.MTSOURCE, key, ComponentMessagesDTO.class);
		    			}
		    		}
	    		}
	    	} catch (VIPCacheException | DataException | ParseException e1) {
	    		// TODO Auto-generated catch block
	    		LOGGER.error(e1.getMessage(), e1);
	    		
	    	}
	    	
	    	
	    }