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

The following are top voted examples for showing how to use org.springframework.scheduling.annotation.Async. 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: spring-io   File: MailService.java   Source Code and License 7 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        log.warn("Email could not be sent to user '{}'", to, e);
    }
}
 
Example 2
Project: myanmarlottery   File: ScheduleServiceImpl.java   Source Code and License 7 votes vote down vote up
@Async
@Override
public Future<List<GetPrizeDTO>> scheduleItems(ScheduleItem item) throws InterruptedException {
    log.info("Start Schedule with : " +item.getRecipientID());
    log.info("query Type " + item.getQueryType());
    Future<List<GetPrizeDTO>> result = new AsyncResult<>(new ArrayList<>());
    if(item.getQueryType() == ConstantUtil.NORMAL_QUERY) {
        result = new AsyncResult<>(resultService.findPrizeByResultType(item.getLotteryType(), item.getParam().toArray(new String[]{})));
    } else if(item.getQueryType() == ConstantUtil.CODE_RANGE_QUERY) {
        result = new AsyncResult<>(resultService.findPrizesByCode(item.getParam().get(0), item.getParam().get(1), item.getParam().get(2), item.getLotteryType()));
    } else if(item.getQueryType() == ConstantUtil.POINT_RANGE_QUERY) {
        result = new AsyncResult<>(resultService.findPrizesByPoints(item.getParam().get(0), item.getParam().get(1), item.getParam().get(2), item.getLotteryType()));
    }
    // remove from db after finding result.
    deleteScheduleItem(item.getRecipientID());
    return result;
}
 
Example 3
Project: jwala   File: GroupStateNotificationServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Async
@SuppressWarnings("unchecked")
public void retrieveStateAndSend(final Identifier id, final Class aClass) {
    LOGGER.debug("Synchronizing on {} and {}...", id, aClass);
    synchronized (lockObject) {
        LOGGER.debug("Thread locked on {} and {}...!", id, aClass);
        final List<JpaGroup> groups;
        if (Jvm.class.getName().equals(aClass.getName())) {
            final JpaJvm jvm = jvmCrudService.getJvm(id);
            groups = jvm.getGroups();
        } else if (WebServer.class.getName().equals(aClass.getName())) {
            final JpaWebServer webServer = webServerCrudService.getWebServerAndItsGroups(id.getId());
            groups = webServer.getGroups();
        } else {
            final String errMsg = "Invalid class parameter: " + aClass.getName() + "!";
            LOGGER.error(errMsg);
            throw new GroupStateNotificationServiceException(errMsg);
        }
        fetchStates(groups, true);
    }
    LOGGER.debug("Thread locked on {} and {} released!", id, aClass);
}
 
Example 4
Project: jhipster-microservices-example   File: MailService.java   Source Code and License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example 5
Project: REST-Web-Services   File: MailServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Async
@Override
public void sendMailWithNewPassword(
        @NotBlank @Email final String email,
        @NotBlank final String newPassword
) {
    log.info("Called with e-mail {}, newPassword {}", email, newPassword);

    try {
        final JavaMailSenderImpl sender = new JavaMailSenderImpl();

        final MimeMessage message = sender.createMimeMessage();

        final MimeMessageHelper helper = new MimeMessageHelper(message);

        helper.setTo(email);
        helper.setSubject("Recover password");
        helper.setText("Your new password: " + "<b>" + newPassword + "</b>", true);

        sendMail(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
 
Example 6
Project: c4sg-services   File: AsyncEmailServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Sends an email message asynchronously through SendGrid.
 * Status Code: 202	- ACCEPTED: Your message is both valid, and queued to be delivered.
 *
 * @param from      email address from which the message will be sent.
 * @param recipient array of strings containing the recipients of the message.
 * @param subject   subject header field.
 * @param text      content of the message.
 */
@Async
public void send(String from, String recipient, String replyTo, String subject, String text) throws IOException {

    Email emailFrom = new Email(from);
    String emailSubject = subject;
    Email emailTo = new Email(recipient);

    Content emailContent = new Content("text/html", text);
    Mail mail = new Mail(emailFrom, emailSubject, emailTo, emailContent);
    if (!replyTo.isEmpty()) {
        Email emailReplyTo = new Email(replyTo);
        mail.setReplyTo(emailReplyTo);
    }

    SendGrid sg = new SendGrid(sendgridApiKey);
    Request request = new Request();
    request.setMethod(Method.POST);
    request.setEndpoint("mail/send");
    request.setBody(mail.build());

    sg.api(request);
}
 
Example 7
Project: Spring-5.0-Cookbook   File: EmployeeServiceImpl.java   Source Code and License 6 votes vote down vote up
@Async
@Override
public void addEmployee(EmployeeForm empForm) {
	
	Employee emp = new Employee();
	emp.setDeptId(empForm.getEmpId());
	emp.setFirstName(empForm.getFirstName());
	emp.setLastName(empForm.getLastName());
	emp.setAge(empForm.getAge());
	emp.setBirthday(empForm.getBirthday());
	emp.setEmail(empForm.getEmail());
	emp.setDeptId(empForm.getDeptId());
	emp.setEmpId(empForm.getEmpId());
	try {
		System.out.println("service:addEmployee task executor: " + Thread.currentThread().getName());
		System.out.println("processing for 1000 ms");
		System.out.println("addEmployee @Async login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Thread.sleep(1000);
	} catch (InterruptedException e) {
	
		e.printStackTrace();
	}
	employeeDaoImpl.addEmployeeBySJI(emp);
}
 
Example 8
Project: IPPR2016   File: ExternalCommunicatorServiceImpl.java   Source Code and License 6 votes vote down vote up
@Async
@Override
public void handleExternalOutputMessage(final ExternalCommunicatorMessage message) {
  LOG.debug("Received request for external out message [{}]", message);

  final Long messageFlowId = getMessageFlowId(message.getTransferId());
  final Long configId = getActiveConfig(messageFlowId);

  final Map<String, InternalObject> businessObjects = new HashMap<>();
  message.getBusinessObjects().stream().forEachOrdered(bo -> {
    final Map<String, InternalField> fields = new HashMap<>();
    bo.getFields().stream().forEachOrdered(field -> {
      fields.put(field.getName(), new InternalField(field.getName(),
          DataType.valueOf(field.getType()), field.getValue()));
    });
    businessObjects.put(bo.getName(), new InternalObject(bo.getName(), fields));
  });

  composeSupervisorActor.tell(new ComposeMessageCreateCommand(message.getTransferId(),
      new InternalData(businessObjects), configId), ActorRef.noSender());
}
 
Example 9
Project: Spring-5.0-Cookbook   File: EmployeeServiceImpl.java   Source Code and License 6 votes vote down vote up
@Async
@Override
public void addEmployee(EmployeeForm empForm) {
	
	Employee emp = new Employee();
	emp.setDeptId(empForm.getEmpId());
	emp.setFirstName(empForm.getFirstName());
	emp.setLastName(empForm.getLastName());
	emp.setAge(empForm.getAge());
	emp.setBirthday(empForm.getBirthday());
	emp.setEmail(empForm.getEmail());
	emp.setDeptId(empForm.getDeptId());
	emp.setEmpId(empForm.getEmpId());
	try {
		System.out.println("service:addEmployee task executor: " + Thread.currentThread().getName());
		System.out.println("processing for 1000 ms");
		System.out.println("addEmployee @Async login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Thread.sleep(1000);
	} catch (InterruptedException e) {
	
		e.printStackTrace();
	}
	employeeDaoImpl.addEmployeeBySJI(emp);
}
 
Example 10
Project: OperatieBRP   File: SelectieRunJobServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Async("selectiejob")
public void start() {
    LOGGER.info("start selectie run service: ");
    BrpNu.set();
    Thread.currentThread().setName("Selectie Job Runner");
    final SelectieJobRunStatus status = selectieJobRunStatusService.newStatus();
    Selectie selectie = null;
    try {
        selectie = selectieService.bepaalSelectie();
        status.setStartDatum(new Date());
        status.setSelectieRunId(selectie.getSelectierun().getId());
        startSelectie(selectie);
        LOGGER.info("einde selectie run service: " + selectie.getSelectierun().getId());
    } finally {
        status.setEindeDatum(new Date());
        if (selectie != null) {
            selectieService.eindeSelectie(selectie);
        }
    }
}
 
Example 11
Project: IPPR2016   File: ProcessServiceImpl.java   Source Code and License 6 votes vote down vote up
@Transactional
@Async
@Override
public Future<List<TaskDTO>> getTasksOfUser(final Long userId) {
  final CompletableFuture<List<TaskDTO>> future = new CompletableFuture<>();

  final TasksOfUserMessage.Request request = new TasksOfUserMessage.Request(userId);

  PatternsCS.ask(userSupervisorActor, request, Global.TIMEOUT).toCompletableFuture()
      .whenComplete((msg, exc) -> {
        if (exc == null) {
          future.complete(((TasksOfUserMessage.Response) msg).getTasks());
        } else {
          future.completeExceptionally(exc);
        }
      });

  return future;
}
 
Example 12
Project: devoxxus-jhipster-microservices-demo   File: MailService.java   Source Code and License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}'", to, e);
    }
}
 
Example 13
Project: obog-manager   File: MailService.java   Source Code and License 6 votes vote down vote up
/**
 * パスワードリセット案内メールを送信します。
 *
 * @param request パスワードリセット要求
 */
@Async
void sendPasswordResetMail(PasswordResetRequest request) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setReplyTo(appReply);
    message.setTo(request.getMembership().getEmail());
    message.setSubject("【パスワードリセット】Java研修 Go研修 OB・OG会");
    message.setText(request.getMembership().getName() + " さん\n\n" +
            "パスワードリセットの要求を受け付けました。\n" +
            "下記 URL から 24 時間以内にパスワードリセットを行ってください。\n\n" +
            appUrl + "/#!" + ResetPasswordView.VIEW_NAME + "/" + request.getToken() + "\n" +
            "※トップページにリダイレクトされてしまう場合は、トップページを開いた画面 (タブ) のアドレス欄に" +
            "上記 URL を張り付けて移動してください。\n\n" +
            "本メールに関するお問合せ先: " + appReply + "\n" +
            "Java研修 Go研修 OB・OG会");
    try {
        mailSender.send(message);
    } catch (MailException e) {
        exceptionHandler.accept(e);
    }
}
 
Example 14
Project: cfsummiteu2017   File: AsyncDeploymentServiceImpl.java   Source Code and License 6 votes vote down vote up
@Async
@Override
public void asyncCreateInstance(DeploymentServiceImpl deploymentService, ServiceInstance serviceInstance,
                                   Map<String, String> parameters, Plan plan, PlatformService platformService) {
	progressService.startJob(serviceInstance);

	try {
		deploymentService.syncCreateInstance(serviceInstance, parameters, plan, platformService);
	} catch (Exception e) {
		progressService.failJob(serviceInstance,
				"Internal error during Instance creation, please contact our support.");

		log.error("Exception during Instance creation", e);
		return;
	}
	progressService.succeedProgress(serviceInstance);
}
 
Example 15
Project: buenojo   File: MailService.java   Source Code and License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example 16
Project: osoon   File: UserFileService.java   Source Code and License 6 votes vote down vote up
@Async
public String createThumbnail(UserFile userFile) {
    String path = userFile.getPath();
    Path originalImagePath = Paths.get(properties.getUploadFileRootPath(), path);

    try {
        BufferedImage originalImage = ImageIO.read(originalImagePath.toFile());
        if (originalImage != null) {
            BufferedImage thumbnailImage = this.createThumbnailImage(originalImage, 300, 200);
            String ext = path.substring(path.lastIndexOf(".") + 1);
            Path thumbNailPath = Paths.get(properties.getUploadFileRootPath(), userFile.getThumbnailPath());
            ImageIO.write(thumbnailImage, ext, Files.newOutputStream(thumbNailPath));
            return thumbNailPath.toString();
        }
    } catch (IOException e) {
        logger.error("Failed to create thumbnail of '{}'", path);
    }

    return "";
}
 
Example 17
Project: IPPR2016   File: ProcessServiceImpl.java   Source Code and License 6 votes vote down vote up
@Transactional
@Async
@Override
public Future<ProcessInfoDTO> stopProcess(final Long piId) {
  final CompletableFuture<ProcessInfoDTO> future = new CompletableFuture<>();

  final ProcessStopMessage.Request request = new ProcessStopMessage.Request(piId);

  PatternsCS.ask(processSupervisorActor, request, Global.TIMEOUT).toCompletableFuture()
      .whenComplete((msg, exc) -> {
        if (exc == null) {
          userSupervisorActor.tell(request, null);
          future.complete(((ProcessStopMessage.Response) msg).getProcess());
        } else {
          future.completeExceptionally(exc);
        }
      });

  return future;
}
 
Example 18
Project: sctalk   File: MessageServerCluster.java   Source Code and License 6 votes vote down vote up
/**
 * 查询用户在线状态
 * 
 * @param fromUserId 用户ID
 * @param userIdList 查询列表
 * @return
 * @since  1.0
 */
@Async
public ListenableFuture<List<IMBaseDefine.UserStat>> userStatusReq(Long fromUserId, List<Long> userIdList) {
    
    logger.debug("查询用户在线状态, user_cnt={}", userIdList.size());
    
    List<IMBaseDefine.UserStat> userStatList = new ArrayList<>();
    for (Long userId: userIdList) {
        
        UserClientInfoManager.UserClientInfo userClientInfo = userClientInfoManager.getUserInfo(userId);
        IMBaseDefine.UserStat.Builder userStatBuiler = IMBaseDefine.UserStat.newBuilder();
        userStatBuiler.setUserId(userId);
        if (userClientInfo != null) {
            userStatBuiler.setStatus(userClientInfo.getStatus());
        } else {
            userStatBuiler.setStatus(IMBaseDefine.UserStatType.USER_STATUS_OFFLINE);
        }
        
        userStatList.add(userStatBuiler.build());
    }
    
    AsyncResult<List<IMBaseDefine.UserStat>> result = new AsyncResult<>(userStatList);
    return result;
}
 
Example 19
Project: tulingchat   File: MailUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 发送文本邮件  setCc 抄送 setBcc 密送
 */
@Async("mailAsync")
public void sendSimpleMail(String to, String subject, String content) {
	SimpleMailMessage message = new SimpleMailMessage();
	message.setFrom(from);
	message.setTo(to);
	message.setBcc(from);
	message.setSubject(subject);
	message.setText(content);
	message.setSentDate(new Date());
	try {
		mailSender.send(message);
		logger.info("简单邮件已经发送。");
	} catch (Exception e) {
		logger.error("发送简单邮件时发生异常!", e);
	}

}
 
Example 20
Project: Microservices-with-JHipster-and-Spring-Boot   File: MailService.java   Source Code and License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        log.warn("Email could not be sent to user '{}'", to, e);
    }
}
 
Example 21
Project: codemotion-2017-taller-de-jhipster   File: MailService.java   Source Code and License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example 22
Project: patient-portal   File: MailService.java   Source Code and License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example 23
Project: sentry   File: MailService.java   Source Code and License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}'", to, e);
    }
}
 
Example 24
Project: pathological-reports   File: RecoverPasswordService.java   Source Code and License 5 votes vote down vote up
@Async
@Transactional
public void recoverPasswordBy(String email) throws EmailException {
	User user = userService.findByEmail(email);

	if (user != null) {
		RecoverPassword recoverPassword = new RecoverPassword(user);

		emailService.send(email, recoverPassword.getToken());
		recoverPasswordRepository.save(recoverPassword);
	}
}
 
Example 25
Project: xm-uaa   File: MailService.java   Source Code and License 5 votes vote down vote up
/**
 * Send password reset email.
 *
 * @param user object which stores info about user
 * @param url application url
 * @param tenantName tenant name
 * @param rid transaction id (use for logging)
 */
@Async
public void sendPasswordResetMail(User user, String url, String tenantName, String rid) {
    MDCUtil.putRid(rid);
    log.info("Sending password reset email to '{}'", user.getEmail());
    sendEmailFromTemplate(
        user,
        "passwordResetEmail",
        "email.reset.title",
        generateFrom(tenantName),
        user.getEmail(),
        url,
        tenantName
    );
}
 
Example 26
Project: IPPR2016   File: OwlImportGatewayCallerImpl.java   Source Code and License 5 votes vote down vote up
@Async
public Future<ResponseEntity<Boolean>> importProcessModel(
    final ImportProcessModelDTO processModelDTO, final HttpHeaderUser headerUser) {
  URIBuilder uri = null;
  try {
    uri = new URIBuilder(gatewayConfig.getProcessModelStorageAddress()).setPath("/import");
  } catch (final URISyntaxException e) {
    LOG.error(e.getMessage());
  }

  final HttpHeaders header = headerUser.getHttpHeaders();
  return createRequest(uri, HttpMethod.POST, processModelDTO, Boolean.class, header);
}
 
Example 27
Project: device-modbus   File: BaseService.java   Source Code and License 5 votes vote down vote up
@Async
public void attemptToInitialize() {
	
	// count the attempt
	setInitAttempts(getInitAttempts() + 1);
	logger.debug("initialization attempt " + getInitAttempts());

	// first - get the service information or register service with metadata
	if(getService() != null) {
		// if we were able to get the service data we're registered
		setRegistered(true);
		// second - invoke any custom initialization method 
		setInitialized(initialize(getServiceId()));
	}

	// if both are successful, then we're done
	if(isRegistered() && isInitialized()) {
		logger.info("initialization successful.");
	} else {
		// otherwise see if we need to keep going
		if((getInitRetries() == 0) || (getInitAttempts() < getInitRetries())) {
			logger.debug("initialization unsuccessful. sleeping " + getInitInterval());
			try {
				Thread.sleep(getInitInterval());
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
			// start up the next thread
			attemptToInitialize();

		} else {
			// here, we've failed and run out of retries, so just be done.
			logger.info("initialization unsuccessful after " + getInitAttempts() + " attempts.  Giving up.");
			// TODO: what do we do here? exit?
			Application.exit(-1);
		}
	} 
}
 
Example 28
Project: jhipster-microservices-example   File: MailService.java   Source Code and License 5 votes vote down vote up
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
    String content = templateEngine.process(templateName, context);
    String subject = messageSource.getMessage(titleKey, null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);

}
 
Example 29
Project: IPPR2016   File: ProcessEngineCallerImpl.java   Source Code and License 5 votes vote down vote up
@Async
public Future<ResponseEntity<StateObjectDTO>> getStateObjectOfUserInProcess(
    final HttpHeaderUser headerUser, final Long piId, final Long userId)
    throws URISyntaxException {
  final URIBuilder uri = new URIBuilder(gatewayConfig.getProcessEngineAddress())
      .setPath("/processes/task/" + piId + "/" + userId);

  final HttpHeaders header = headerUser.getHttpHeaders();
  return createRequest(uri, HttpMethod.GET, null, StateObjectDTO.class, header);
}
 
Example 30
Project: IPPR2016   File: ProcessEngineCallerImpl.java   Source Code and License 5 votes vote down vote up
@Async
public Future<ResponseEntity<Long>> getAmountOfFinishedProcessesInRange(final Long hoursbefore)
    throws URISyntaxException {
  final URIBuilder uri = new URIBuilder(gatewayConfig.getProcessEngineAddress())
      .setPath("processes/count/finished/" + hoursbefore);

  return createRequest(uri, HttpMethod.GET, null, Long.class, null);
}
 
Example 31
Project: canal-mongo   File: DataService.java   Source Code and License 5 votes vote down vote up
@Async("myTaskAsyncPool")
public Future<Integer> doAsyncTask(String tableName, List<EventData> dataList, String destination) {
    try {
        MDC.put("destination", destination);
        logger.info("thread: " + Thread.currentThread().getName() + " is doing job :" + tableName);
        for (EventData eventData : dataList) {
            SpringUtil.doEvent(eventData.getPath(), eventData.getDbObject());
        }
    } catch (Exception e) {
        logger.error("thread:" + Thread.currentThread().getName() + " get Exception", e);
        return new AsyncResult(0);
    }
    return new AsyncResult(1);
}
 
Example 32
Project: TorgCRM-Server   File: MailService.java   Source Code and License 5 votes vote down vote up
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
    String content = templateEngine.process(templateName, context);
    String subject = messageSource.getMessage(titleKey, null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);

}
 
Example 33
Project: Your-Microservice   File: AuthenticationController.java   Source Code and License 5 votes vote down vote up
/**
 * saveTokenHistory
 *
 * @param token Token to re-verify to obtain Claims Set to Persist as a Token History Element.
 */
@Async
protected void saveTokenHistory(String token) {
    try {
        /**
         * Generate a Token History Entry based upon our Current Supplied Token.
         */
        JWTClaimsSet claimsSet = yourMicroserviceToken.verifyToken(token);
        if (claimsSet == null) {
            LOGGER.warn("Unable to Verify Token to retrieve ClaimsSet to Persist Token History, Ignoring.");
            return;
        }
        /**
         * Instantiate the Token History Entity.
         */
        YourEntityTokenHistory yourEntityTokenHistory = new YourEntityTokenHistory();
        yourEntityTokenHistory.setJti(claimsSet.getJWTID());
        yourEntityTokenHistory.setSubject(claimsSet.getSubject());
        yourEntityTokenHistory.setStatus(YourEntityTokenStatus.ACTIVE);
        yourEntityTokenHistory.setIssuedAt(claimsSet.getIssueTime());
        yourEntityTokenHistory.setExpiration(claimsSet.getExpirationTime());
        yourEntityTokenHistory.setNotUsedBefore(claimsSet.getNotBeforeTime());
        yourEntityTokenHistory.setLastUsed(claimsSet.getIssueTime());
        yourEntityTokenHistory.setUsageCount(1L);
        /**
         * Persist the Entity.
         */
        yourEntityTokenHistory = identityProviderEntityManager.createTokenHistory(yourEntityTokenHistory);
        if (yourEntityTokenHistory == null) {
            LOGGER.warn("Unable to Persist Token History Entity, Ignoring.");
        }
    } catch (YourMicroserviceInvalidTokenException ite) {
        LOGGER.warn("Invalid Your Microservice Token Exception:'{}', Encountered while attempting " +
                "to persist Token History Entity.", ite.getMessage(), ite);
    }
}
 
Example 34
Project: daros-dynamic   File: DynamicLoadClassAsync.java   Source Code and License 5 votes vote down vote up
@Async("register")
public CompletableFuture<List<String>> compileGroovy(String path) {
    logger.info("Start compile groovy file: " + path);
    List<String> listClassName = DynamicUtil.compileGroovyFile(path);

    try {
        Thread.sleep(1000L);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    logger.info("Complete compile groovy file: " + path);
    return CompletableFuture.completedFuture(listClassName);
}
 
Example 35
Project: device-bacnet   File: BaseService.java   Source Code and License 5 votes vote down vote up
@Async
public void attemptToInitialize() {
	
	// count the attempt
	setInitAttempts(getInitAttempts() + 1);
	logger.debug("initialization attempt " + getInitAttempts());

	// first - get the service information or register service with metadata
	if(getService() != null) {
		// if we were able to get the service data we're registered
		setRegistered(true);
		// second - invoke any custom initialization method 
		setInitialized(initialize(getServiceId()));
	}

	// if both are successful, then we're done
	if(isRegistered() && isInitialized()) {
		logger.info("initialization successful.");
	} else {
		// otherwise see if we need to keep going
		if((getInitRetries() == 0) || (getInitAttempts() < getInitRetries())) {
			logger.debug("initialization unsuccessful. sleeping " + getInitInterval());
			try {
				Thread.sleep(getInitInterval());
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
			// start up the next thread
			attemptToInitialize();

		} else {
			// here, we've failed and run out of retries, so just be done.
			logger.info("initialization unsuccessful after " + getInitAttempts() + " attempts.  Giving up.");
			// TODO: what do we do here? exit?
			Application.exit(-1);
		}
	} 
}
 
Example 36
Project: device-bluetooth   File: BaseService.java   Source Code and License 5 votes vote down vote up
@Async
public void attemptToInitialize() {

  // count the attempt
  setInitAttempts(getInitAttempts() + 1);
  logger.debug("initialization attempt " + getInitAttempts());

  // first - get the service information or register service with metadata
  if (getService() != null) {
    // if we were able to get the service data we're registered
    setRegistered(true);
    // second - invoke any custom initialization method
    setInitialized(initialize(getServiceId()));
  }

  // if both are successful, then we're done
  if (isRegistered() && isInitialized()) {
    logger.info("initialization successful.");
  } else {
    // otherwise see if we need to keep going
    if ((getInitRetries() == 0) || (getInitAttempts() < getInitRetries())) {
      logger.debug("initialization unsuccessful. sleeping " + getInitInterval());
      try {
        Thread.sleep(getInitInterval());
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
      // start up the next thread
      attemptToInitialize();

    } else {
      // here, we've failed and run out of retries, so just be done.
      logger.info("initialization unsuccessful after " + getInitAttempts()
          + " attempts.  Giving up.");
      // TODO: what do we do here? exit?
      Application.exit(-1);
    }
  }
}
 
Example 37
Project: device-mqtt   File: BaseService.java   Source Code and License 5 votes vote down vote up
@Async
public void attemptToInitialize() {

  // count the attempt
  setInitAttempts(getInitAttempts() + 1);
  logger.debug("initialization attempt " + getInitAttempts());

  // first - get the service information or register service with metadata
  if (getService() != null) {
    // if we were able to get the service data we're registered
    setRegistered(true);
    // second - invoke any custom initialization method
    setInitialized(initialize(getServiceId()));
  }

  // if both are successful, then we're done
  if (isRegistered() && isInitialized()) {
    logger.info("initialization successful.");
  } else {
    // otherwise see if we need to keep going
    if ((getInitRetries() == 0) || (getInitAttempts() < getInitRetries())) {
      logger.debug("initialization unsuccessful. sleeping " + getInitInterval());
      try {
        Thread.sleep(getInitInterval());
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
      // start up the next thread
      attemptToInitialize();

    } else {
      // here, we've failed and run out of retries, so just be done.
      logger.info(
          "initialization unsuccessful after " + getInitAttempts() + " attempts.  Giving up.");
      // TODO: what do we do here? exit?
      Application.exit(-1);
    }
  }
}
 
Example 38
Project: xm-ms-entity   File: ProfileEventProducer.java   Source Code and License 5 votes vote down vote up
/**
 * Send event to kafka.
 * @param content the event data
 */
@Async
public void send(String content) {
    if (StringUtils.isNoneBlank(content)) {
        log.debug("Sending kafka event with data {} to topic {}", content, topicName);
        template.send(topicName, content);
    }
}
 
Example 39
Project: speakTogether   File: MailService.java   Source Code and License 5 votes vote down vote up
@Async
public void sendActivationEmail(User user) {
    log.debug("Sending activation e-mail to '{}'", user.getEmail());
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
    String content = templateEngine.process("activationEmail", context);
    String subject = messageSource.getMessage("email.activation.title", null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);
}
 
Example 40
Project: Code4Health-Platform   File: MailService.java   Source Code and License 5 votes vote down vote up
@Async
public void sendActivationEmail(User user) {
    log.debug("Sending activation e-mail to '{}'", user.getEmail());
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
    String content = templateEngine.process("activationEmail", context);
    String subject = messageSource.getMessage("email.activation.title", null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);
}
 
Example 41
Project: devoxxus-jhipster-microservices-demo   File: MailService.java   Source Code and License 5 votes vote down vote up
@Async
public void sendActivationEmail(User user) {
    log.debug("Sending activation e-mail to '{}'", user.getEmail());
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
    String content = templateEngine.process("activationEmail", context);
    String subject = messageSource.getMessage("email.activation.title", null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);
}
 
Example 42
Project: IPPR2016   File: StartUpRunner.java   Source Code and License 5 votes vote down vote up
@Async
@Transactional
@Override
public void run(final ApplicationArguments args) throws Exception {
  LOG.info(
      "##################################################################################################################");
  LOG.info("Start up of already running processes and users");

  final List<ProcessInstance> processes = Lists.newArrayList(
      processInstanceRepository.getProcessesWithState(ProcessInstanceState.ACTIVE.name()));

  processes.stream()
      .map(process -> PatternsCS.ask(processSupervisorActor,
          new ProcessWakeUpMessage.Request(process.getPiId()), Global.TIMEOUT)
          .toCompletableFuture())
      .forEachOrdered(response -> {
        futures.add(response);
        handleProcessResponse(response);
      });

  final Set<Subject> subjects =
      processes.stream().map(ProcessInstance::getSubjects).flatMap(List::stream)
          .filter(subject -> subject.getUser() != null).collect(Collectors.toSet());

  subjects.stream()
      .map(subject -> PatternsCS.ask(userSupervisorActor,
          new UserActorWakeUpMessage.Request(subject.getUser()), Global.TIMEOUT)
          .toCompletableFuture())
      .forEachOrdered(response -> {
        futures.add(response);
        handleUserResponse(response);
      });

  CompletableFuture.allOf(Iterables.toArray(futures, CompletableFuture.class)).thenRun(() -> {
    final List<SubjectState> subjectStatesWithTimeout =
        subjectStateRepository.getSubjectStatesWithTimeout();
    subjectStatesWithTimeout.stream().forEach(this::notifyTimeoutScheduler);
  });
}
 
Example 43
Project: Spring-5.0-Cookbook   File: DepartmentServiceImpl.java   Source Code and License 5 votes vote down vote up
@Async
@Override
public void addDepartment(DepartmentForm dept) {
	System.out.println("addDepartment @Async login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
	Department deptData = new Department();
	deptData.setDeptId(dept.getDeptId());
	deptData.setName(dept.getName());
	departmentDaoImpl.addDepartmentByJT(deptData);
}
 
Example 44
Project: IPPR2016   File: ProcessEngineCallerImpl.java   Source Code and License 5 votes vote down vote up
@Async
public Future<ResponseEntity<ProcessInfoDTO>> stopProcess(final HttpHeaderUser headerUser,
    final Long piId) throws URISyntaxException {
  final URIBuilder uri =
      new URIBuilder(gatewayConfig.getProcessEngineAddress()).setPath("/processes/stop/" + piId);

  final HttpHeaders header = headerUser.getHttpHeaders();
  return createRequest(uri, HttpMethod.POST, null, ProcessInfoDTO.class, header);
}
 
Example 45
Project: Spring-5.0-Cookbook   File: DepartmentServiceImpl.java   Source Code and License 5 votes vote down vote up
@Async
@Override
public void addDepartment(DepartmentForm dept) {
	System.out.println("addDepartment @Async login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
	Department deptData = new Department();
	deptData.setDeptId(dept.getDeptId());
	deptData.setName(dept.getName());
	departmentDaoImpl.addDepartmentByJT(deptData);
}
 
Example 46
Project: IPPR2016   File: ProcessEngineCallerImpl.java   Source Code and License 5 votes vote down vote up
@Async
public Future<ResponseEntity<ProcessStartedDTO>> startProcess(
    @RequestBody final ProcessStartDTO processStartDTO, final HttpHeaderUser headerUser)
    throws URISyntaxException {
  LOG.debug("Create request to start process instance");

  final URIBuilder uri =
      new URIBuilder(gatewayConfig.getProcessEngineAddress()).setPath("/processes/startProcess");

  final HttpHeaders header = headerUser.getHttpHeaders();
  return createRequest(uri, HttpMethod.POST, processStartDTO, ProcessStartedDTO.class, header);
}
 
Example 47
Project: spring-io   File: MailService.java   Source Code and License 5 votes vote down vote up
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
    String content = templateEngine.process(templateName, context);
    String subject = messageSource.getMessage(titleKey, null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);

}
 
Example 48
Project: JenkinsHue   File: HueServiceImpl.java   Source Code and License 5 votes vote down vote up
@Async
@Override
public void updateLamp(LampWithHueUniqueId lamp, ScenarioConfigDTO config) {
	if(config != null) {
		for (PHBridge bridge : bridges) {
			PHBridgeResourcesCache resourceCache = bridge.getResourceCache();
			List<PHLight> allLights = resourceCache.getAllLights();

			String url = "http://" + bridge.getResourceCache().getBridgeConfiguration().getIpAddress() + "/api/"
					+ bridge.getResourceCache().getBridgeConfiguration().getUsername() + "/lights";
			
			bridge.doHTTPGet(url, new PHHTTPListener() {
				@Override
				public void onHTTPResponse(String jsonResponse) {
					JSONObject object = new JSONObject(jsonResponse);
					for (PHLight light : allLights) {
						light.setUniqueId(object.optJSONObject(light.getIdentifier()).optString("uniqueid"));
						
						if (light.getUniqueId().equals(lamp.getHueUniqueId())) {
							updateLamp(bridge, light, config);
						}
					}
				}
			});
		}
	}
}
 
Example 49
Project: klask-io   File: AsyncCrawler.java   Source Code and License 5 votes vote down vote up
@Async("taskExecutor")
    public void executeCrawler(ICrawler crawler){
        Future<CrawlerResult> result = crawler.getResult();

//        if(result != null && !result.isDone() && !result.isCancelled() && result.){
//            log.warn("The crawler is yet indexing files... No more jobs can be submitted");
//        } else {
            CrawlerResult crawlerResult = crawler.start();
            crawler.setResult(new AsyncResult<>(crawlerResult));

//        }
//        return result;
    }
 
Example 50
Project: che-starter   File: CheServerClient.java   Source Code and License 5 votes vote down vote up
@Async
public void startCheServer(OpenShiftClient client, String namespace, String keycloakToken)
        throws RouteNotFoundException {
    if (toggle.isMultiTenant(keycloakToken)) {
        return; // che-starter is not supposed to start multi-tenant che-server
    }
    cheDeploymentConfig.deployCheIfSuspended(client, namespace);
}
 
Example 51
Project: seldon-core   File: PredictiveUnitBean.java   Source Code and License 5 votes vote down vote up
@Async
private Future<Boolean> sendFeedbackAsync(Feedback feedback, PredictiveUnitState state) throws InterruptedException, ExecutionException, InvalidProtocolBufferException{
	System.out.println("NODE " + state.name + ": entered feedback");
	List<PredictiveUnitState> children = new ArrayList<PredictiveUnitState>();
	List<Future<Boolean>> returns = new ArrayList<Future<Boolean>>();
	
	// Getting the actual implementation (microservice or hardcoded? )
	PredictiveUnitImpl implementation = predictorConfig.getImplementation(state);
	if (implementation == null){ implementation = this; }
			
	// First we determine children we will send feedback to according to routingDict info
	int routing = feedback.getResponse().getMeta().getRoutingMap().getOrDefault(state.name, -1);
	
	// TODO: Throw exception if routing is invalid (<-1 or > n_children)
	if (routing == -1){
		children = state.children;
	}
	else if (routing>=0) {
		children.add(state.children.get(routing));
	}
	
	// First we call sendFeebackAsync on children
	for (PredictiveUnitState child : children){
		returns.add(sendFeedbackAsync(feedback,child));
	}
	
	// Then we wait for our own feedback
	implementation.doSendFeedback(feedback, state);
	
	//Then we wait for children feedback
	for (Future<Boolean> ret : returns){
		ret.get();
	}
	
	// Finally we store the feedback metrics
	doStoreFeedbackMetrics(feedback,state);
	
	return new AsyncResult<>(true);
}
 
Example 52
Project: buenojo   File: MailService.java   Source Code and License 5 votes vote down vote up
@Async
public void sendActivationEmail(User user, String baseUrl) {
    log.debug("Sending activation e-mail to '{}'", user.getEmail());
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable("user", user);
    context.setVariable("baseUrl", baseUrl);
    String content = templateEngine.process("activationEmail", context);
    String subject = messageSource.getMessage("email.activation.title", null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);
}
 
Example 53
Project: springboot-start   File: AsyncTask.java   Source Code and License 5 votes vote down vote up
@Async
public Future<String> doTaskThree() throws Exception {
    System.out.println("开始做任务三");
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
    return new AsyncResult<>("任务三完成");
}
 
Example 54
Project: codemotion-2017-taller-de-jhipster   File: MailService.java   Source Code and License 5 votes vote down vote up
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
    String content = templateEngine.process(templateName, context);
    String subject = messageSource.getMessage(titleKey, null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);

}
 
Example 55
Project: IPPR2016   File: ProcessModelStorageCallerImpl.java   Source Code and License 5 votes vote down vote up
@Async
public Future<ResponseEntity<FieldPermissionDTO[]>> getPermissions() throws URISyntaxException {
  final URIBuilder uri =
      new URIBuilder(gatewayConfig.getProcessModelStorageAddress()).setPath("/permissions");

  return createRequest(uri, HttpMethod.GET, null, FieldPermissionDTO[].class, null);
}
 
Example 56
Project: Microservices-with-JHipster-and-Spring-Boot   File: MailService.java   Source Code and License 5 votes vote down vote up
@Async
public void sendActivationEmail(User user) {
    log.debug("Sending activation email to '{}'", user.getEmail());
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
    String content = templateEngine.process("activationEmail", context);
    String subject = messageSource.getMessage("email.activation.title", null, locale);
    sendEmail(user.getEmail(), subject, content, false, true);
}
 
Example 57
Project: support-rulesengine   File: CommandExecutor.java   Source Code and License 5 votes vote down vote up
@Async
public void fireCommand(String deviceId, String commandId, String body) {
  logger.info(
      "Sending request to:  " + deviceId + "for command:  " + commandId + " with body: " + body);
  try {
    // for now - all rule engine requests are puts
    forwardRequest(deviceId, commandId, body, true);
  } catch (Exception exception) {
    logger.error("Problem sending command to the device service " + exception);
  }
}
 
Example 58
Project: spring-boot-completablefuture   File: UserController.java   Source Code and License 5 votes vote down vote up
@Async(AsyncConfiguration.TASK_EXECUTOR_CONTROLLER)
@GetMapping(value = REQUEST_PATH_API_USERS_INDIVIDUAL_USER,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public CompletableFuture<ResponseEntity> getUser(@PathVariable final String userId) {
    return userService
            .findOneById(userId)
            .thenApply(mapMaybeUserToResponse)
            .exceptionally(handleGetUserFailure.apply(userId));
}
 
Example 59
Project: newblog   File: AsyncServiceImpl.java   Source Code and License 5 votes vote down vote up
@Async
@Override
public void updatebloghits(Integer blogid) {
    try {
        blogMapper.updatehits(blogid);
    } catch (Exception e) {
        logger.error("更新阅读次数错误", e);
    }
}
 
Example 60
Project: logger   File: RwFile.java   Source Code and License 5 votes vote down vote up
@Async
@Scheduled(initialDelay=2000, fixedDelay=50)
public void writeFile() {
    files.forEach(file -> {
        try {
            String content = " " + file.getName() + " rw_: " + step.incrementAndGet() + System.getProperty("line.separator");
            content = Constants.DATE_FORMAT_TIME.format(new Date()) + " " + this.getRandomType() + content;
            Files.write(file.toPath(), content.getBytes(), StandardOpenOption.APPEND);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}