org.springframework.scheduling.annotation.Async Java Examples
The following examples show how to use
org.springframework.scheduling.annotation.Async.
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: KafkaConsumer.java From cubeai with Apache License 2.0 | 6 votes |
@KafkaListener(topics = {"async-task-topic"}, group = "umu") @Async public void receive(String message) { log.info("Kafka received message='{}'", message); JSONObject taskCommand = JSONObject.parseObject(message); String taskType = taskCommand.getString("taskType"); String taskUuid = taskCommand.getString("taskUuid"); if (null != taskUuid) { if (taskType.equals("ucumos-deploy")) { this.deployService.deploy(taskUuid, taskCommand.getBoolean("isPublic")); } if (taskType.equals("ucumos-lcm-stop")) { this.lifeCircleManagementService.stop(taskUuid, taskCommand.getString("deploymentUuid")); } } }
Example #2
Source File: Dmas.java From dbys with GNU General Public License v3.0 | 6 votes |
@Async public void xzbcdm(String url, String player) { String json = HtmlUtils.getHtmlContentNp(url); JSONObject jsonObject = JSON.parseObject(json); JSONArray comments = jsonObject.getJSONArray("comments"); int maxc = comments.size(); for (int j = 0; j < maxc; j++) { JSONObject comment = comments.getJSONObject(j); Dan d = new Dan(); d.setReferer("https://v.qq.com"); d.setIp("::ffff:111.111.111.111"); d.setType(0); d.setTime(comment.getDouble("timepoint")); d.setAuthor(comment.getString("opername")); d.setPlayer(player); d.setText(comment.getString("content")); d.setColor(14277107); d.setDate(currentTimeMillis()); mongoTemplate.insert(d); } }
Example #3
Source File: Scheduler.java From dbys with GNU General Public License v3.0 | 6 votes |
@Async @Scheduled(fixedDelay = 60000) public void cronJobSchedule() { Set tagids = redisTemplate.opsForSet().members("tagids"); redisTemplate.delete("tagids"); Object[] das = tagids.toArray(); for (Object s : das) { JSONObject jsonObject = JSON.parseObject(String.valueOf(s)); String tagid = jsonObject.getString("tagid"); String player = (jsonObject.getString("player")); int timestamp = 0; boolean flg = true; while (flg) { String url = "http://mfm.video.qq.com/danmu?otype=json&target_id=" + tagid + "×tamp=" + timestamp; timestamp += 30; as.xzbcdm(url, player); if (timestamp > 60 * 120) { flg = false; } } redisTemplate.opsForSet().add("oktagids", tagid); redisTemplate.delete("danmaku" + player); } }
Example #4
Source File: HelperService.java From staffjoy with MIT License | 6 votes |
@Async(AppConfig.ASYNC_EXECUTOR_NAME) public void sendEmailAsync(AccountDto a, CompanyDto c) { EmailRequest emailRequest = EmailRequest.builder() .to("[email protected]") .name("") .subject(String.format("%s from %s just joined Staffjoy", a.getName(), c.getName())) .htmlBody(String.format("Name: %s<br>Phone: %s<br>Email: %s<br>Company: %s<br>App: https://app.staffjoy.com/#/companies/%s/employees/", a.getName(), a.getPhoneNumber(), a.getEmail(), c.getName(), c.getId())) .build(); BaseResponse baseResponse = null; try { baseResponse = mailClient.send(emailRequest); } catch (Exception ex) { String errMsg = "Unable to send email"; logException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { logError(logger, baseResponse.getMessage()); } }
Example #5
Source File: ServiceHelper.java From staffjoy with MIT License | 6 votes |
@Async(AppConfig.ASYNC_EXECUTOR_NAME) public void trackEventAsync(String event) { String userId = AuthContext.getUserId(); if (StringUtils.isEmpty(userId)) { // Not an action performed by a normal user // (noop - not an view) return; } TrackEventRequest trackEventRequest = TrackEventRequest.builder() .userId(userId).event(event).build(); BaseResponse resp = null; try { resp = accountClient.trackEvent(trackEventRequest); } catch (Exception ex) { String errMsg = "fail to trackEvent through accountClient"; handleErrorAndThrowException(logger, ex, errMsg); } if (!resp.isSuccess()) { handleErrorAndThrowException(logger, resp.getMessage()); } }
Example #6
Source File: NettyHandlerService.java From momo-cloud-permission with Apache License 2.0 | 6 votes |
@Async("threadPoolTaskExecutor") public Future<String> onlineCount(String symbol) { Future<String> future = new AsyncResult<>("更新首页用户在线数量"); Map<String, Channel> channelMapAll = ChannelManager.getAllChannel(); if (channelMapAll != null && !channelMapAll.isEmpty()) { int onlineConut = 0; if (StringUtils.isEmpty(symbol)) { onlineConut = ChannelManager.sizeChannel(); } else if ("-".equals(symbol)) { onlineConut = ChannelManager.sizeChannel() - 1; } else if ("+".equals(symbol)) { onlineConut = ChannelManager.sizeChannel() + 1; } else { onlineConut = ChannelManager.sizeChannel(); } IMMessage imMessage = new IMMessage(RedisKeyEnum.NETTY_ONLINE_COUNT.getExpireTime(), onlineConut, null); channelMapAll.forEach((s, channel) -> ChannelManager.ctxWrite(channel, imMessage)); } return future; }
Example #7
Source File: MailService.java From cubeai with Apache License 2.0 | 6 votes |
@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 #8
Source File: ColumnService.java From mapper-generator-javafx with Apache License 2.0 | 5 votes |
/** * columns 单个写入文件 * * @param dataSource 数据源 * @param table 表信息 */ @Async void downLoadColumnsToFileSingle(DataSource dataSource, Table table) { File columnsFile = BaseConstants.getColumnsFile(dataSource, table.getTableName()); String tableNameColumnsMapStr = JSONArray.toJSONString(table.getColumns(), true); try { FileUtils.writeStringToFile(columnsFile, tableNameColumnsMapStr); } catch (IOException e) { log.error("columns download 失败"); } }
Example #9
Source File: HelperService.java From staffjoy with MIT License | 5 votes |
@Async(AppConfig.ASYNC_EXECUTOR_NAME) void mailGreetingAsync(AccountDto accountDto) { String email = accountDto.getEmail(); String name = accountDto.getName(); String subject = "Staffjoy Greeting"; String htmlBody = BotConstant.GREETING_EMAIL_TEMPLATE; this.sendMail(email, name, subject, htmlBody); }
Example #10
Source File: ServiceHelper.java From staffjoy with MIT License | 5 votes |
@Async(AppConfig.ASYNC_EXECUTOR_NAME) public void alertRemovedShiftAsync(AlertRemovedShiftRequest alertRemovedShiftRequest) { BaseResponse baseResponse = null; try { baseResponse = botClient.alertRemovedShift(alertRemovedShiftRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about removed shift"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } }
Example #11
Source File: LoginSuccessListener.java From spring-microservice-exam with MIT License | 5 votes |
/** * 异步记录登录日志 * * @param logInfo logInfo * @param userDto userDto * @author tangyi * @date 2019/05/30 23:30 */ @Async public void saveLoginInfo(Log logInfo, UserDto userDto) { try { userServiceClient.saveLog(logInfo); userServiceClient.updateLoginInfo(userDto); } catch (Exception e) { log.error(e.getMessage(), e); } }
Example #12
Source File: AsyncService.java From code with Apache License 2.0 | 5 votes |
/** * @Async 告诉 Spring 这是一个异步方法 * 默认使用 Spring 内的线程池 * threadName:task-1 * * @Async("BeanName") 从 IOC 容器中指定线程池 * threadName:myThreadPool-1 * */ @Async("myThreadPool") public void hello() { String threadName = Thread.currentThread().getName(); long threadId = Thread.currentThread().getId(); System.out.println(getClass()+" threadName:" + threadName + " , threadId:" + threadId); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(getClass()+" threadName:" + threadName + " , threadId:" + threadId + " ,处理数据中..."); }
Example #13
Source File: AsyncServiceImpl.java From ProjectStudy with MIT License | 5 votes |
@Override @Async("threadPoolTaskExecutor") public Future<String> task4() throws Exception { logger.info("task4开始执行"); Thread.sleep(3000); logger.info("task4执行结束"); return new AsyncResult<String>("task4 success"); }
Example #14
Source File: TableService.java From mapper-generator-javafx with Apache License 2.0 | 5 votes |
/** * 把tables信息记录到文件 */ @Async void downLoadToFileBatch(DataSource dataSource, List<Table> tables) { try { for (Table table : tables) { String tablesStr = JSON.toJSONString(table, true); FileUtils.writeStringToFile(BaseConstants.getTableFile(dataSource, table.getTableName()), tablesStr, StandardCharsets.UTF_8.toString()); } } catch (IOException e) { log.error("写入表文件错误", e); } }
Example #15
Source File: NotifyService.java From mall with MIT License | 5 votes |
/** * 短信模版消息通知 * * @param phoneNumber 接收通知的电话号码 * @param notifyType 通知类别,通过该枚举值在配置文件中获取相应的模版ID * @param params 通知模版内容里的参数,类似"您的验证码为{1}"中{1}的值 */ @Async public void notifySmsTemplate(String phoneNumber, NotifyType notifyType, String[] params) { if (smsSender == null) { return; } String templateIdStr = getTemplateId(notifyType, smsTemplate); if (templateIdStr == null) { return; } int templateId = Integer.parseInt(templateIdStr); smsSender.sendWithTemplate(phoneNumber, templateId, params); }
Example #16
Source File: BlockService.java From WeBASE-Node-Manager with Apache License 2.0 | 5 votes |
/** * get block from chain by groupId * ThreadPool configuration in /base/config/BeanConfig */ @Async(value = "mgrAsyncExecutor") public void pullBlockByGroupId(CountDownLatch latch, int groupId) { log.debug("start pullBlockByGroupId groupId:{}", groupId); try { //max block in chain BigInteger maxChainBlock = frontInterface.getLatestBlockNumber(groupId); //next block BigInteger nextBlock = getNextBlockNumber(groupId); //pull block while (Objects.nonNull(maxChainBlock) && maxChainBlock.compareTo(nextBlock) >= 0) { log.debug("continue pull block. maxChainBlock:{} nextBlock:{}", maxChainBlock, nextBlock); Thread.sleep(cProperties.getPullBlockSleepTime()); pullBlockByNumber(groupId, nextBlock); nextBlock = getNextBlockNumber(groupId); //reset maxChainBlock if (maxChainBlock.compareTo(nextBlock) < 0) { maxChainBlock = frontInterface.getLatestBlockNumber(groupId); } } } catch (Exception ex) { log.error("fail pullBlockByGroupId. groupId:{} ", groupId, ex); }finally { // finish one group, count down latch.countDown(); } log.debug("end pullBlockByGroupId groupId:{}", groupId); }
Example #17
Source File: GrayConfigCenter.java From AthenaServing with Apache License 2.0 | 5 votes |
/** * 删除灰度配置 * * @param path * @param regionList */ @Async public void deleteGrayConfig(String path, String grayGroupId, List<Region> regionList) { String pushId = SnowflakeIdWorker.getId(); Map<String, String> map = new HashMap<>(); map.put("path", path); map.put("pushId", pushId); map.put("grayGroupId", grayGroupId); this.batchPost(DELETE_DATA_URL, map, regionList); }
Example #18
Source File: SubnetServiceImp.java From alcor with Apache License 2.0 | 5 votes |
@Async @Override public void ipFallback(int ipVersion, String rangeId, String ipAddr) { String ipManagerServiceUrl = ipUrl + ipVersion + "/" + rangeId + "/" + ipAddr; restTemplate.delete(ipManagerServiceUrl, IpAddrRequest.class); String ipRangeDeleteServiceUrl = ipUrl + "range/" + rangeId; restTemplate.delete(ipRangeDeleteServiceUrl, IpAddrRangeRequest.class); }
Example #19
Source File: SmsUtil.java From ProjectStudy with MIT License | 5 votes |
/** * 异步发送短信 * * @param phone * @param code * @return void * @throws * @author wliduo[[email protected]] * @date 2020/5/20 10:53 */ @Async public void sendCode(String phone, String code) { logger.info("开始发送验证码..."); // 模拟调用接口发验证码的耗时 try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("发送成功: {}", phone); }
Example #20
Source File: ColumnService.java From mapper-generator-javafx with Apache License 2.0 | 5 votes |
/** * 把columns文件从磁盘删除 */ @Async void deleteColumnFile(DataSource dataSource, String tableName) { try { FileUtils.forceDelete(BaseConstants.getColumnsFile(dataSource, tableName)); } catch (IOException e) { log.error("删除字段文件错误", e); } }
Example #21
Source File: NotifyService.java From mall with MIT License | 5 votes |
/** * 短信消息通知 * * @param phoneNumber 接收通知的电话号码 * @param message 短消息内容,这里短消息内容必须已经在短信平台审核通过 */ @Async public void notifySms(String phoneNumber, String message) { if (smsSender == null) return; smsSender.send(phoneNumber, message); }
Example #22
Source File: MailService.java From alchemy with Apache License 2.0 | 5 votes |
@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 #23
Source File: SystemCoreLogListener.java From momo-cloud-permission with Apache License 2.0 | 5 votes |
@Async @Order @EventListener(SystemCoreLogEvent.class) public void saveSysLog(SystemCoreLogEvent event) { SystemCoreLogDO sysLog = (SystemCoreLogDO) event.getSource(); log.info("AOP logs {}", JSONObject.toJSONString(sysLog)); }
Example #24
Source File: CinemaSocketAsync.java From dbys with GNU General Public License v3.0 | 5 votes |
@Async public void sendRoomMsgPassAuthor(int id,String msg){ String authorId = CinemaSocket.ROOM_POOL.get(id).getAuthorId(); CinemaSocket.ROOM_POOL.get(id).getSockets().forEach(sid->{ if(!sid.equals(authorId)){ CinemaSocket.POOL.get(sid).sendMessage(msg); } }); }
Example #25
Source File: TableService.java From mapper-generator-javafx with Apache License 2.0 | 5 votes |
/** * 把 table 文件从磁盘删除 */ @Async void deleteTableFile(DataSource dataSource, String tableName) { try { FileUtils.forceDelete(BaseConstants.getTableFile(dataSource, tableName)); } catch (IOException e) { log.error("删除表文件错误", e); } }
Example #26
Source File: EventPublishingTestExecutionListenerIntegrationTests.java From spring-analysis-note with MIT License | 5 votes |
@BeforeTestMethod("event.testContext.testMethod.name == 'testWithFailingAsyncEventListener'") @Async public void beforeTestMethodWithAsyncFailure(BeforeTestMethodEvent event) throws Exception { this.listener.beforeTestMethod(event.getSource()); throw new RuntimeException(String.format("Asynchronous exception for test method [%s] in thread [%s]", event.getTestContext().getTestMethod().getName(), Thread.currentThread().getName())); }
Example #27
Source File: AnnotationDrivenEventListenerTests.java From spring-analysis-note with MIT License | 5 votes |
@EventListener @Async public void handleAsync(AnotherTestEvent event) { assertNotEquals(event.content, Thread.currentThread().getName()); this.eventCollector.addEvent(this, event); this.countDownLatch.countDown(); }
Example #28
Source File: TestServiceImpl.java From springBoot with MIT License | 5 votes |
@Async @Override public void asyncTask() { long startTime = System.currentTimeMillis(); try { //模拟耗时 Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println(Thread.currentThread().getName() + ":void asyncTask(),耗时:" + (endTime - startTime)); }
Example #29
Source File: ColumnService.java From mapper-generator-javafx with Apache License 2.0 | 5 votes |
/** * columns 批量写入文件 * * @param dataSource 数据源 * @param tableNameColumnsMap columnsMap */ @Async void downLoadColumnsToFileBatch(DataSource dataSource, Map<String, List<Column>> tableNameColumnsMap) { tableNameColumnsMap.forEach((tableName, columns) -> { File columnsFile = BaseConstants.getColumnsFile(dataSource, tableName); String tableNameColumnsMapStr = JSONArray.toJSONString(columns, true); try { FileUtils.writeStringToFile(columnsFile, tableNameColumnsMapStr); } catch (IOException e) { log.error("columns download 失败"); } }); }
Example #30
Source File: MailService.java From cubeai with Apache License 2.0 | 5 votes |
@Async public void sendPasswordResetMail(User user) { log.debug("Sending password reset email to '{}'", user.getEmail()); // sendEmailFromTemplate(user, "passwordResetEmail", "email.reset.title"); String subject = "CubeAI密码重置"; String content = "你好!\n\n" + " 你正在进行密码重置,重置密钥:" + user.getResetKey() + "。\n" + " 请妥善保管,切勿向他人泄露!\n\n" + "谢谢!\n\n" + "CubeAI ★ 智立方\n\n" + "(本邮件为系统后台发送,请勿回复!)"; sendEmail(user.getEmail(), subject, content, false, false); }