一、任务

1、异步任务

  1. package com.yunche.task.service;
  2. import org.springframework.stereotype.Service;
  3. /**
  4. * @ClassName: TaskService
  5. * @Description:
  6. * @author: yunche
  7. * @date: 2019/02/05
  8. */
  9. @Service
  10. public class TaskService {
  11. public void doSomething() {
  12. try {
  13. Thread.sleep(3000);
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. System.out.println("I am doing something");
  18. }
  19. }
  1. package com.yunche.task.controller;
  2. import com.yunche.task.service.TaskService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. /**
  7. * @ClassName: TaskController
  8. * @Description:
  9. * @author: yunche
  10. * @date: 2019/02/05
  11. */
  12. @RestController
  13. public class TaskController {
  14. @Autowired
  15. public TaskService taskService;
  16. @GetMapping("/say")
  17. public String say() {
  18. taskService.doSomething();
  19. return "Hello world!";
  20. }
  21. }

访问:http://localhost:8080/say,由于处理 doSomething() 方法会阻塞 3 秒,所以浏览器 3 秒后才会得到字符串

Hello world!。为了加快其返回结果,可以将 doSomething() 方法修改为异步任务执行,首先在方法体上面加上

@Async注解,然后还需要添加@EnableAsync 注解,开启使用异步注解。

  1. @Async
  2. public void doSomething() {
  3. try {
  4. Thread.sleep(3000);
  5. } catch (InterruptedException e) {
  6. e.printStackTrace();
  7. }
  8. System.out.println("I am doing something");
  9. }
  1. package com.yunche.task;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.scheduling.annotation.EnableAsync;
  5. @EnableAsync
  6. @SpringBootApplication
  7. public class TaskApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(TaskApplication.class, args);
  10. }
  11. }

此时访问:http://localhost:8080/say,就可以立即得到返回结果了。

2、定时任务

定时任务类似于异步任务也是需要两个注解:@Scheduled@EnableScheduling。需要注意的是该怎么计划定时任务的时间,即如何书写cron表达式,规则如下图:

来看下例子:

  1. package com.yunche.task.service;
  2. import org.springframework.scheduling.annotation.Scheduled;
  3. import org.springframework.stereotype.Service;
  4. /**
  5. * @ClassName: ScheduleService
  6. * @Description:
  7. * @author: yunche
  8. * @date: 2019/02/05
  9. */
  10. @Service
  11. public class ScheduleService {
  12. /**
  13. * cron 表达式时间的设置分为 6 个部分:
  14. * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).每个部分以空格分隔。
  15. *
  16. */
  17. @Scheduled(cron = "0 * * * * 1-5") // 代表每周的周 1 到周 5 的每个小时的每个整分执行任务
  18. public void test() {
  19. System.out.println("我是定时任务。。。");
  20. }
  21. }
  1. package com.yunche.task;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.scheduling.annotation.EnableAsync;
  5. import org.springframework.scheduling.annotation.EnableScheduling;
  6. @EnableScheduling
  7. @EnableAsync
  8. @SpringBootApplication
  9. public class TaskApplication {
  10. public static void main(String[] args) {
  11. SpringApplication.run(TaskApplication.class, args);
  12. }
  13. }

运行主程序,发现确实是整分的时候打印语句。下面是几个实例。

  1. * 0 0/5 14,18 * * ?】 每天 14 点整,和 18 点整,每隔 5 分钟执行一次
  2. * 0 15 10 ? * 1-6 每个月的周一至周六 10:15 分执行一次
  3. * 0 0 2 ? * 6L】每个月的最后一个周六凌晨 2 点执行一次
  4. * 0 0 2 LW * ?】每个月的最后一个工作日凌晨 2 点执行一次
  5. * 0 0 2-4 ? * 1#1】每个月的第一个周一凌晨 2 点到 4 点期间,每个整点都执行一次;

3、邮件任务

需要导入 spring-boot-starter-mail 场景启动器,pom 文件:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-mail</artifactId>
  4. </dependency>

下面用 163 邮箱给 qq 邮箱发送邮件:首先需要在发送方的邮箱设置中开启一些服务,并保存一个第三方授权码。

  1. spring:
  2. mail:
  3. username: xxxx@163.com
  4. password: 第三方授权码
  5. host: smtp.163.com

接下来根据邮件是否包含附件,分为 2 种情况:

  • 不带附件,简单文本内容:

    1. package com.yunche.task;
    2. import org.junit.Test;
    3. import org.junit.runner.RunWith;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.test.context.SpringBootTest;
    6. import org.springframework.mail.SimpleMailMessage;
    7. import org.springframework.mail.javamail.JavaMailSenderImpl;
    8. import org.springframework.scheduling.annotation.Scheduled;
    9. import org.springframework.test.context.junit4.SpringRunner;
    10. @RunWith(SpringRunner.class)
    11. @SpringBootTest
    12. public class TaskApplicationTests {
    13. @Autowired
    14. JavaMailSenderImpl mailSender;
    15. @Test
    16. public void contextLoads() {
    17. //简单消息使用 SimpleMailMessage 类
    18. SimpleMailMessage message = new SimpleMailMessage();
    19. message.setFrom("发送方@163.com");
    20. message.setSubject("我是主题");
    21. message.setText("我是普通的文本内容,我想说:你好");
    22. message.setTo("接收者@qq.com");
    23. mailSender.send(message);
    24. System.out.println("发送成功");
    25. }
    26. }
  • 带附件的邮件:

    1. @Test
    2. public void test01() throws MessagingException {
    3. MimeMessage message= mailSender.createMimeMessage();
    4. //第二个参数,开启文件上传功能
    5. MimeMessageHelper helper = new MimeMessageHelper(message, true);
    6. try {
    7. //上传一张图片到附件中
    8. helper.addAttachment("66418885_p0.png", new File("C:\\Users\\Administrator\\Desktop\\wallpaper\\66418885_p0.png"));
    9. //第二个参数,文本内容以 HTML 方式显示
    10. helper.setText("<p style='color:red'> 我是红色的内容哦 </p>", true);
    11. helper.setSubject("我是主题");
    12. helper.setFrom("发送方@163.com");
    13. helper.setTo("收件方@qq.com");
    14. } catch (MessagingException e) {
    15. e.printStackTrace();
    16. }
    17. mailSender.send(message);
    18. System.out.println("发送成功");
    19. }

二、参考资料

尚硅谷.Spring Boot 高级

Spring Boot 与任务的更多相关文章

  1. 玩转spring boot——快速开始

    开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...

  2. 【微框架】之一:从零开始,轻松搞定SpringCloud微框架系列--开山篇(spring boot 小demo)

    Spring顶级框架有众多,那么接下的篇幅,我将重点讲解SpringCloud微框架的实现 Spring 顶级项目,包含众多,我们重点学习一下,SpringCloud项目以及SpringBoot项目 ...

  3. 玩转spring boot——开篇

    很久没写博客了,而这一转眼就是7年.这段时间并不是我没学习东西,而是园友们的技术提高的非常快,这反而让我不知道该写些什么.我做程序已经有十几年之久了,可以说是彻彻底底的“程序老炮”,至于技术怎么样?我 ...

  4. 玩转spring boot——结合redis

    一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...

  5. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  6. 玩转spring boot——结合JPA入门

    参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...

  7. 玩转spring boot——结合JPA事务

    接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  8. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

  9. 玩转spring boot——结合jQuery和AngularJs

    在上篇的基础上 准备工作: 修改pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  10. 玩转spring boot——MVC应用

    如何快速搭建一个MCV程序? 参照spring官方例子:https://spring.io/guides/gs/serving-web-content/ 一.spring mvc结合thymeleaf ...

随机推荐

  1. 关于camera senor的power引脚问题

    <CamDevie> <HardWareInfo> <Sensor> <SensorName name="OV5640" >< ...

  2. 【Android】自己定义View

    翻译自:http://developer.android.com/training/custom-views/index.html 一)创建view类 一个设计良好的自己定义view与其它的类一样.它 ...

  3. 音乐播放器之myeclipse项目

    音乐播放器: 这个音乐播放器是用myeclipse打开的项目.假设有问题记得改掉文件的路径名.还有假设图片不显示也可能是图片的路径名不正确,如音乐无法播放也可能是路径名不正确.总之这个游戏有文件的引用 ...

  4. Vijos 1523 贪吃的九头龙 【树形DP】

    贪吃的九头龙 背景 安徽省芜湖市第二十七中学测试题 NOI 2002 贪吃的九头龙(dragon) Description:OfficialData:OfficialProgram:Converted ...

  5. luogu 3953 逛公园

    noip2017 D1T3 逛公园 某zz选手看到数据范围直接就最短路计数了,结果写错了爆零 题目大意: N个点M条边构成的有向图,且没有自环和重边.其中1号点是起点,N号点是公园的终点,每条边有一个 ...

  6. [App Store Connect帮助]三、管理 App 和版本(6.3)转让 App:接受 App 转让

    您必须在转让发起的 60 天内接受转让. 必要职能:“帐户持有人”职能.请参见职能权限. 以具有“帐户持有人”职能用户的身份登录至 App Store Connect. 系统会显示一条通知,指示 Ap ...

  7. ACM_下一个排列

    The Next Permutation Time Limit: 2000/1000ms (Java/Others) Problem Description: For this problem, yo ...

  8. magento 翻译使用实例

    在自定义的模块中若想要使用翻译,需在config.xml中加入如下配置 <config> <adminhtml> //后台 <translate> <modu ...

  9. Android 性能优化(2)性能工具之「Hierarchy Viewer 」Optimizing Your UI:分析哪个view有性能问题,查看屏幕上某像素点的坐标,颜色等

    Optimizing Your UI In this document Using Hierarchy Viewer Running Hierarchy Viewer and choosing a w ...

  10. 如何调试ajax 和php

    ###ex11_1_main.php <html><head><meta http-equiv="Content-Type" content=&quo ...