使用 maven 创建 SpringBoot 项目,引入 Web 场景启动器。

异步任务

1、编写异步服务类,注册到 IoC 容器:

package zze.springboot.task.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    @Async // 标识方法将会异步执行
    public void hello() {
        try {
            Thread.sleep();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello");
    }
}

zze.springboot.task.service.AsyncService

2、使用注解开启异步任务支持:

package zze.springboot.task;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync // 开启异步任务支持
@SpringBootApplication
public class TaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(TaskApplication.class, args);
    }

}

zze.springboot.task.TaskApplication

3、编写控制器测试:

package zze.springboot.task.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import zze.springboot.task.service.AsyncService;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/hello")
    public String testAsyncHello(){
        asyncService.hello();
        return "执行完毕";
        /*
        访问 localhost:8080/hello
            a、立即返回了 “执行完毕”,并没有因为 asyncService.hello() 方法中的线程 sleep 等待 3 秒。
            b、3 秒后控制台输出 hello
        OK,异步任务执行成功
         */
    }
}

zze.springboot.task.controller.AsyncController

定时任务

1、编写定时任务类,使用 Cron 表达式指定任务执行时机,注册到 IoC 容器:

package zze.springboot.task.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class ScheduleService {
    @Scheduled(cron = "*/3 * * * * ?")  // 编写 cron 表达式,每 3 秒执行一次
    public void test(){
        Date now = new Date();
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        System.out.println(timeFormat.format(now));
    }
}

zze.springboot.task.service.ScheduleService

2、使用注解开启定时任务支持:

package zze.springboot.task;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling // 开启定时任务支持
@SpringBootApplication
public class TaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(TaskApplication.class, args);
    }

}

zze.springboot.task.TaskApplication

3、启动项目测试:

hello at ::
hello at ::
hello at ::
hello at ::
/*
每间隔 3 秒控制台会执行 hello 方法
*/

test

SpringBoot 中的定时任务 Cron 表达式与任务调度框架 Quartz 的 Cron 表达式规则相似,可参考【Quartz 表达式】。

但它们有一处区别是:

  • SpringBoot 任务的 Cron 表达式中星期部分 1-6 为周一到周六,0 和 7都为周日。
  • Quartz 框架的 Cron 表达式中星期部分 1-7 为周日到周六。

邮件任务

邮件的自动配置类为 org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration 。

下面以 QQ 邮箱给 GMail 邮箱发送邮件为例。

1、引入 Mail 场景启动器:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、获取 qq 邮箱授权码,登录进入 qq 邮箱,进入设置,选择账户,选择生成授权码:

3、邮箱相关配置:

spring.mail.username=632404164@qq.com
// 使用生成的授权码
spring.mail.password=nffutccjfabdbchc
spring.mail.host=smtp.qq.com

# qq 邮箱需要开启 ssl
spring.mail.properties.mail.smtp.sll.enable=true

application.properties

4、测试:

package zze.springboot.mail;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailApplicationTests {

    @Autowired
    JavaMailSender javaMailSender;

    // 发送普通文本内容
    @Test
    public void test1() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 设置邮件标题
        mailMessage.setSubject("标题");
        // 设置邮件内容
        mailMessage.setText("hello");

        mailMessage.setFrom("632404164@qq.com");
        mailMessage.setTo("zhangzhongen326@gmail.com");
        javaMailSender.send(mailMessage);

    }

    // 发送 html 内容带附件
    @Test
    public void test2() throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        // 设置标题
        mimeMessageHelper.setSubject("标题");
        // 设置内容
        mimeMessageHelper.setText("<font color='red'>hello</font>",true);

        // 设置附件,可设置多个
        mimeMessageHelper.addAttachment("1.jpg", new File("C:\\Users\\Administrator\\Desktop\\1mail.png"));

        mimeMessageHelper.setFrom("632404164@qq.com");
        mimeMessageHelper.setTo("zhangzhongen326@gmail.com");
        javaMailSender.send(mimeMessage);

    }

}

test

java框架之SpringBoot(14)-任务的更多相关文章

  1. java框架之SpringBoot(1)-入门

    简介 Spring Boot 用来简化 Spring 应用开发,约定大于配置,去繁从简,just run 就能创建一个独立的.产品级别的应用. 背景: J2EE 笨重的开发.繁多的配置.低下的开发效率 ...

  2. java框架之SpringBoot(2)-配置

    规范 SpringBoot 使用一个全局的配置文件,配置文件名固定为 application.properties 或 application.yml .比如我们要配置程序启动使用的端口号,如下: s ...

  3. java框架之SpringBoot(3)-日志

    市面上的日志框架 日志抽象层 日志实现 JCL(Jakarta Commons Logging).SLF4J(Simple Logging Facade For Java).JBoss-Logging ...

  4. java框架之SpringBoot(4)-资源映射&thymeleaf

    资源映射 静态资源映射 查看 SpringMVC 的自动配置类,里面有一个配置静态资源映射的方法: @Override public void addResourceHandlers(Resource ...

  5. java框架之SpringBoot(5)-SpringMVC的自动配置

    本篇文章内容详细可参考官方文档第 29 节. SpringMVC介绍 SpringBoot 非常适合 Web 应用程序开发.可以使用嵌入式 Tomcat,Jetty,Undertow 或 Netty ...

  6. java框架之SpringBoot(15)-安全及整合SpringSecurity

    SpringSecurity介绍 Spring Security 是针对 Spring 项目的安全框架,也是 Spring Boot 底层安全模块默认的技术选型.它可以实现强大的 Web 安全控制.对 ...

  7. java框架之SpringBoot(16)-分布式及整合Dubbo

    前言 分布式应用 在分布式系统中,国内常用 Zookeeper + Dubbo 组合,而 SpringBoot 推荐使用 Spring 提供的分布式一站式解决方案 Spring + SpringBoo ...

  8. Java - 框架之 SpringBoot 攻略day01

          Spring-Boot 攻略 day01 spring-boot   一. 基本配置加运行   1. 导入配置文件(pom.xml 文件中)   <parent> <gr ...

  9. 【java框架】SpringBoot(5)--SpringBoot整合分布式Dubbo+Zookeeper

    1.理论概述 1.1.分布式 分布式系统是若干独立计算机的集合,这些计算机对于用户来讲就像单个系统. 由多个系统集成成一个整体,提供多个功能,组合成一个板块,用户在使用上看起来是一个服务.(比如淘宝网 ...

随机推荐

  1. 【原创 Hadoop&Spark 动手实践 9】Spark SQL 程序设计基础与动手实践(上)

    [原创 Hadoop&Spark 动手实践 9]SparkSQL程序设计基础与动手实践(上) 目标: 1. 理解Spark SQL最基础的原理 2. 可以使用Spark SQL完成一些简单的数 ...

  2. 猿题库从 Objective-C 到 Swift 的迁移

    猿题库从 Objective-C 到 Swift 的迁移 引言 相信没有人会怀疑,Swift 是 iOS 开发未来的主流语言,但是由于 Swift 语言的不断变化以及庞大的迁移成本,真正把项目迁移到 ...

  3. 【iCore4 双核心板_ARM】例程三十五:HTTP_IAP_ARM实验——更新升级STM32

    实验现象: 核心代码: int main(void) { led.initialize(); //LED³õʼ»¯ key.initialize(); if(ARM_KEY_STATE == KEY ...

  4. EditText小记

    今天在编写样式的时候,需要设置数据输入为单行,但是 Android:singleLine=”true” 显示为已过期,提示使用 android:maxLines=“1” 代替,但是设置后却发现并没有效 ...

  5. 释放锁标记只有在Synchronized代码结束或者调用wait()。

    释放锁标记只有在Synchronized代码结束或者调用wait(). 注意锁标记是自己不会自动释放,必须有通知. 注意在程序中判定一个条件是否成立时要注意使用WHILE要比使用IF要严密. WHIL ...

  6. MongoDB学习总结(二)

    前言:学习札记! MongoDB学习总结(二) 1.  安装.初识 之前写过一篇MongoDB的快速上手文章,里边详细的讲了如何安装.启动MongoDB,这里就不再累述安装过程,简单介绍一下Mongo ...

  7. iOS学习之--字符串的删除替换(字符串的常用处理,删除,替换)

    字符串操作,比较简单,仅做记录! 1.删除 NSString *str1 = @"<hello,wo r d!>"; //删除字符串两端的尖括号 NSMutableSt ...

  8. css3 - 纯css实现一个轮播图

    这是我上一次的面试题.一晃两个月过去了. 从前都是拿原理骗人,把怎么实现的思路说出来. 我今天又被人问到了,才想起来真正码出来.码出来效果说明一切: 以上gif,只用到了5张图片,一个html+css ...

  9. 编译wxWidgets

    打开x64 Native Tools Command Prompt for VS 2017 cd wxWidgets-2.9.5\build\msw nmake -f makefile.vc TARG ...

  10. C# Aspose.Cells.dll Excel操作总结

    简介 Aspose.Cells是一款功能强大的 Excel 文档处理和转换控件,不依赖 Microsoft Excel 环境,支持所有 Excel 格式类型的操作. 下载 Aspose.Cells.d ...