异步任务、定时任务及邮件发送

异步任务

异步任务:

添加异步任务,即开启多线程只需要在方法上添加注解@Async //@Async 告诉Spring是一个异步任务

然后在Main方法上开启此功能即可。

//开启异步任务
@EnableAsync
@SpringBootApplication
public class SpringbootestApplication {

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

}

定时任务

//开启定时任务的支持
@EnableScheduling
//什么时候执行
@Scheduled

首先在Main放上配置注解@EnableScheduling 开启服务的支持

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

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

}

在方法上添加@Scheduled方法规定执行时间

//    秒 分 时 日 月 周几  6个参数
    @Scheduled(cron = "0 09 13 * * 0-7")
    public void Hello()
    {
        System.out.println("Hello");
    }

CRON表达式例子

     每隔1分钟执行一次:0 */1 * * * ?

     每天23点执行一次:0 0 23 * * ?

     每天凌晨1点执行一次:0 0 1 * * ?

     每月1号凌晨1点执行一次:0 0 1 1 * ?

     每月最后一天23点执行一次:0 0 23 L * ?

     每周星期天凌晨1点实行一次:0 0 1 ? * L

     在26分、29分、33分执行一次:0 26,29,33 * * * ?

     每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?

邮件发送

Springboot中使用邮件只需添加依赖

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

邮件的配置

spring.mail.username=邮箱账户
spring.mail.password=客户端授权码,邮箱给定的不是密码
spring.mail.host=smtp.qq.com 设置邮件服务器(不同邮箱不同这里是qq)
#上面三个是必须配置的
spring.mail.port=465  发送的端口
spring.mail.default-encoding=utf-8 编码方式
#开启加密验证 qq邮箱才需要配置
spring.mail.properties.mail.smtp.ssl.enable=true

授权码通过开启POP3/SMTP服务得到,在邮箱设置–账户中可以找到。

邮件发送的实现通过类JavaMailSenderImpl来实现

		//JavaMailSenderImpl 邮件发送实现类
		@Autowired
    JavaMailSenderImpl MailSender;
		//简单邮件的实现
    @Test 
    void contextLoad()
    {
        //配置发送邮件信息
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("发送的标题");
        mailMessage.setText("发送的内容");
        //收件人地址
        mailMessage.setTo("xxxxxxx@qq.com");
        //发件人邮箱,注意applicationContext中的邮箱一致,否则报501错误
        mailMessage.setFrom("xxxxxxx@qq.com");

        MailSender.send(mailMessage);
    }
		//复杂邮件的实现
    @Test 
    void contextLoad2() throws MessagingException {
        //配置发送邮件信息
        MimeMessage message = MailSender.createMimeMessage();

        MimeMessageHelper messageHelper = new MimeMessageHelper(message,"UTF-8");
        messageHelper.setSubject("主题");
        messageHelper.setText("<p style='color:red'>内容</p>");
        //附件
        messageHelper.addAttachment("文件名字",new File("文件地址"));
        messageHelper.setTo("xxxxxxx@qq.com");//收件人地址
        messageHelper.setFrom("xxxxxx@qq.com");//发件人邮箱

        MailSender.send(message);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Celery可以很方便地实现定时任务和批量推送邮件。以下是一个示例代码,演示如何使用Celery定时发送批量邮件: 1. 安装Celery和Redis ```bash pip install celery redis ``` 2. 创建Celery实例 ```python # tasks.py from celery import Celery app = Celery('tasks', broker='redis://localhost:6379/0') ``` 3. 编写发送邮件的函数 ```python # tasks.py import smtplib from email.mime.text import MIMEText @app.task def send_email(recipient, subject, body): # 创建邮件内容 message = MIMEText(body) message['From'] = 'sender@example.com' message['To'] = recipient message['Subject'] = subject # 连接邮件服务器 server = smtplib.SMTP('smtp.example.com', 587) server.starttls() server.login('username', 'password') # 发送邮件 server.sendmail('sender@example.com', recipient, message.as_string()) # 关闭连接 server.quit() ``` 4. 编写定时任务 ```python # tasks.py from datetime import datetime, timedelta @app.task def send_batch_emails(): # 构造邮件列表 recipients = ['user1@example.com', 'user2@example.com', 'user3@example.com'] subject = 'Test Email' body = 'This is a test email.' # 发送邮件 for recipient in recipients: send_email.apply_async(args=[recipient, subject, body]) @app.task def send_periodic_emails(): # 每天10点发送一次邮件 schedule_time = datetime.now().replace(hour=10, minute=0, second=0) if schedule_time < datetime.now(): schedule_time += timedelta(days=1) send_batch_emails.apply_async(eta=schedule_time) ``` 5. 启动Celery ```bash celery -A tasks worker --loglevel=info ``` 6. 定时发送邮件 ```python # 在任意位置调用 send_periodic_emails() 函数即可 from tasks import send_periodic_emails send_periodic_emails.delay() ``` 在上面的代码中,我们使用Celery创建了一个异步任务send_email(),用于发送单个邮件。然后,我们创建了一个异步任务send_batch_emails(),用于批量发送邮件。send_batch_emails()函数遍历收件人列表,为每个收件人创建一个send_email任务,并异步发送邮件。 最后,我们创建了一个定时任务send_periodic_emails(),用于每天10点发送一次邮件。我们使用Celery的apply_async()方法设置任务的执行时间,并在启动Celery后调用该函数即可。 您可以根据自己的需要修改邮件内容、收件人列表和定时任务的时间,并使用类似的方法来实现定时发送批量邮件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值