springboot 2.0+ 用quartz定时发送邮件

Springboot 用quartz定时发送邮件

—————项目目录结构——————

在这里插入图片描述

———————项目配置————————

1、 添加pom依赖

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

2、application.yml配置文件

spring:
  #  定时发送邮件
  mail:
    #发送方qq邮箱需要的授权码,下文3中讲述
    password: **********
    default-encoding: UTF-8
    #qq邮箱用的
    host: smtp.qq.com
    properties:
      mail:
        smtp:
          starttls:
            enable: true
            required: true
          auth: true
    #发送放邮箱
    username: *****@qq.com

3、qq邮箱授权码

3.1 登录qq邮箱后进去主页,点击设置

在这里插入图片描述

3.2 找到邮箱设置,点击账户

在这里插入图片描述

3.3 找到POP3/SMTP服务 点击开启,发送短信就可以获得授权码

在这里插入图片描述

4、 在conf包下新增JobFactory.class

package com.hiQiBlog.conf;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

/**
 * @author ${ww}
 * @Title: JobFactory
 * @Description: TODO
 */
@Component
public class JobFactory extends AdaptableJobFactory {
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
    //生成一个job实例
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        //调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        //进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

5、在config包中新增QuartzConfiguration.class

package com.hiQiBlog.config;



import com.hiQiBlog.conf.JobFactory;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
@Configuration
public class QuartzConfiguration {



    /**
     * @author ${ww}
     * @Title: QuartzConfigration
     * @Description: TODO
     */
    @Configuration
    @EnableScheduling
    public class QuartzConfigration {

        @Autowired
        private JobFactory jobFactory;

        @Bean
        public SchedulerFactoryBean schedulerFactoryBean() {
            SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
            schedulerFactoryBean.setOverwriteExistingJobs(true);
            schedulerFactoryBean.setJobFactory(jobFactory);
            return schedulerFactoryBean;
        }


        // 创建schedule
        @Bean(name = "scheduler")
        public Scheduler scheduler() {
            return schedulerFactoryBean().getScheduler();
        }

    }
}

6、新建SendEmailJob.class

package com.hiQiBlog.job;

import com.hiQiBlog.service.SendEmailSevice;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

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

/**
 * @author ${ww}
 * @Title: HelloJob
 * @Description: TODO
 */
public class SendEmailJob implements  Job {
    @Autowired
    private SendEmailSevice emailService;
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("现在的时间是:" + sf.format(date));
        //具体的业务逻辑
        System.out.println("开始任务");
        //发送邮件的方法
        emailService.sendEmail();
    }
}

7、新建接口层ISendEmailSevice和实现类SendEmailSeviceImpl

package com.hiQiBlog.service;

import com.hiQiBlog.entity.User;

import java.util.List;

public interface ISendEmailSevice {
   //简单邮件
   public boolean sendEmail();
   //发送带附件的复杂的邮件
   public boolean  sendAttachmentMail();
}

package com.hiQiBlog.service.impl;


import com.hiQiBlog.service.ISendEmailSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


@Service
public class SendEmailSeviceImpl implements ISendEmailSevice {
    @Value("${spring.mail.username}")
    private String fromEmail;

    //注入spring发送邮件的对象
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public boolean sendEmail() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //目标邮箱
        simpleMailMessage.setTo("*******@qq.com");
        simpleMailMessage.setFrom(fromEmail);
        //主题
        simpleMailMessage.setSubject("测试");
        simpleMailMessage.setText("utf-8");
        try {
            javaMailSender.send(simpleMailMessage);        //执行发送
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean sendAttachmentMail() {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo("1579258595@qq.com");
            helper.setSubject("测试");
            helper.setText("utf-8");
            helper.setFrom(fromEmail);
//            if(filepath.size()>0){						//读取附件文件(传入文件路径)
//                for (Object string : filepath) {		//遍历文件数组,实现多个附件的添加
//                    FileSystemResource file = new FileSystemResource(string.toString());
//                    String fileName = file.getFilename();//获取文件名
//                    helper.addAttachment(fileName, file);//参数:文件名,文件路径
//                }
//                try {
//                    javaMailSender.send(mimeMessage);		//发送邮件
//                } catch (Exception e) {
//                    return false;						//发送出现异常(或者文件路径不对)
//                }
//                return true;							//成功发送
//            }else {
//                return false;    						//没有附件文件(中断发送)
//            }
            try {
                    javaMailSender.send(mimeMessage);		//发送邮件
                } catch (Exception e) {
                    return false;						//发送出现异常(或者文件路径不对)
                }
                return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            //捕获到创建MimeMessageHelper的异常
//			return false;
            return true;
        }

    }
}

8、新建接口层IQuartzService和实现类QuartzServiceImpl

package com.hiQiBlog.service;

public interface IQuartzService {
    void startJob(String time, String jobName, String group);

    /****
     * 暂停一个任务
     * @param triggerName
     * @param triggerGroupName
     */
    void pauseJob(String triggerName, String triggerGroupName);
    /****
     * 暂停重启一个定时器任务
     * @param triggerName
     * @param triggerGroupName
     */
    void resumeJob(String triggerName, String triggerGroupName);

    /****
     * 删除一个定时器任务,删除了,重启就没什么用了
     * @param triggerName
     * @param triggerGroupName
     */
    void deleteJob(String triggerName, String triggerGroupName);

    /***
     * 根据出发规则匹配任务,立即执行定时任务,暂停的时候可以用
     */
    void doJob(String triggerName, String triggerGroupName);

    /***
     * 开启定时器,这时才可以开始所有的任务,默认是开启的
     */
    void startAllJob();

    /**
     * 关闭定时器,则所有任务不能执行和创建
     */
    void shutdown();
}

package com.hiQiBlog.service.impl;

import com.hiQiBlog.job.SendEmailJob;
import com.hiQiBlog.service.IQuartzService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ${ww}
 * @Title: QuartzServiceImpl
 * @Description: TODO
 */
/**
 SimpleScheduleBuilder是简单调用触发器,它只能指定触发的间隔时间和执行次数;
 CronScheduleBuilder是类似于Linux Cron的触发器,它通过一个称为CronExpression的规则来指定触发规则,通常是每次触发的具体时间;(关于CronExpression,详见:官方,中文网文)
 CalendarIntervalScheduleBuilder是对CronScheduleBuilder的补充,它能指定每隔一段时间触发一次。
 */

@Service
public class QuartzServiceImpl implements IQuartzService {

    @Autowired
    private Scheduler scheduler;
    @Override
    public void startJob(String time, String jobName, String group) {
        try {
            // 创建jobDetail实例,绑定Job实现类
            // 指明job的名称,所在组的名称,以及绑定job类
            JobDetail jobDetail = JobBuilder.newJob(SendEmailJob.class).withIdentity(jobName, group).build();//设置Job的名字和组
            //corn表达式  每x秒执行一次
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time);
            //设置定时任务的时间触发规则
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, group).withSchedule(scheduleBuilder).build();
            System.out.println(scheduler.getSchedulerName());
            // 把作业和触发器注册到任务调度中, 启动调度
            scheduler.scheduleJob(jobDetail, cronTrigger);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /****
     * 暂停一个任务
     * @param triggerName
     * @param triggerGroupName
     */
    @Override
    public void pauseJob(String triggerName, String triggerGroupName) {
        try {
            JobKey jobKey = new JobKey(triggerName, triggerGroupName);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                return;
            }
            System.out.println("开始暂停一个定时器");
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /****
     * 暂停重启一个定时器任务
     * @param triggerName
     * @param triggerGroupName
     */
    @Override
    public void resumeJob(String triggerName, String triggerGroupName) {
        try {
            JobKey jobKey = new JobKey(triggerName, triggerGroupName);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                return;
            }
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    /****
     * 删除一个定时器任务,删除了,重启就没什么用了
     * @param triggerName
     * @param triggerGroupName
     */
    @Override
    public void deleteJob(String triggerName, String triggerGroupName) {
        try {
            JobKey jobKey = new JobKey(triggerName, triggerGroupName);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                return;
            }
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    /***
     * 根据出发规则匹配任务,立即执行定时任务,暂停的时候可以用
     */
    @Override
    public void doJob(String triggerName, String triggerGroupName) {
        try {
            JobKey jobKey = JobKey.jobKey(triggerName, triggerGroupName);
            scheduler.triggerJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    /***
     * 开启定时器,这时才可以开始所有的任务,默认是开启的
     */
    @Override
    public void startAllJob() {
        try {
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭定时器,则所有任务不能执行和创建
     */
    @Override
    public void shutdown() {
        try {
            scheduler.shutdown();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}



8、测试类

package com.hiQiBlog;

import com.hiQiBlog.service.IQuartzService;
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.test.context.junit4.SpringRunner;

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

@Autowired
IQuartzService e;
    /**
     * 发送html格式Email
     */
    @Test
    public void testEmail() throws Exception {
        //参数 第一个是cron表达式 每五秒一次 第二个是job名称 第三个是所在组名称
        e.startJob("*/5 * * * * ? ","zz","zz");
    }

}

好的,动态定时任务一般需要以下几个步骤: 1. 在后端使用 SpringBootQuartz,定义一个定时任务类,继承自 Quartz 的 Job 接口,并实现其中的 execute 方法。 2. 在定时任务类中,编写需要执行的任务逻辑。 3. 在定时任务类中,添加一些参数,用于动态设置定时任务的执行时间和执行频率。这些参数可以通过注解或者配置文件进行设置。 4. 在前端使用 Vue,创建一个页面,用于展示所有已经添加的定时任务,并且可以动态添加、修改和删除定时任务。 5. 在前端页面中,使用 axios 或者其他 AJAX 库,向后端发送添加、修改和删除定时任务的请求。 6. 后端接收到前端的请求后,根据请求的参数,动态创建、修改或删除 Quartz 定时任务。 具体实现可以参照以下步骤: 1. 在后端使用 SpringBootQuartz,定义一个定时任务类,如下所示: ``` @Component public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 编写需要执行的任务逻辑 } } ``` 2. 在定时任务类中,添加一些参数,用于动态设置定时任务的执行时间和执行频率,如下所示: ``` @Component public class MyJob implements Job { @Value("${job.trigger.cron}") private String cronExpression; @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 编写需要执行的任务逻辑 } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } } ``` 在这里,我们使用了 @Value 注解来从配置文件中读取 cron 表达式,然后通过 setter 方法将其设置到定时任务类中。 3. 在前端使用 Vue,创建一个页面,用于展示所有已经添加的定时任务,并且可以动态添加、修改和删除定时任务。具体实现可以参考以下代码: ``` <template> <div> <h2>定时任务列表</h2> <table> <thead> <tr> <th>ID</th> <th>名称</th> <th>状态</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="job in jobs" :key="job.id"> <td>{{ job.id }}</td> <td>{{ job.name }}</td> <td>{{ job.status }}</td> <td> <button @click="editJob(job)">编辑</button> <button @click="deleteJob(job)">删除</button> </td> </tr> </tbody> </table> <button @click="addJob()">添加定时任务</button> <div v-if="showEditDialog"> <h3>{{ dialogTitle }}</h3> <form> <div> <label>名称:</label> <input type="text" v-model="job.name"> </div> <div> <label>状态:</label> <select v-model="job.status"> <option value="启用">启用</option> <option value="停用">停用</option> </select> </div> <div> <label>执行时间:</label> <input type="text" v-model="job.trigger.cron"> </div> <button @click="saveJob()">保存</button> <button @click="closeDialog()">关闭</button> </form> </div> </div> </template> <script> import axios from 'axios' export default { data() { return { jobs: [], job: { id: null, name: '', status: '启用', trigger: { cron: '' } }, showEditDialog: false, dialogTitle: '' } }, created() { this.getJobs() }, methods: { getJobs() { axios.get('/api/jobs') .then(response => { this.jobs = response.data }) .catch(error => { console.log(error) }) }, addJob() { this.job.id = null this.job.name = '' this.job.status = '启用' this.job.trigger.cron = '' this.dialogTitle = '添加定时任务' this.showEditDialog = true }, editJob(job) { this.job.id = job.id this.job.name = job.name this.job.status = job.status this.job.trigger.cron = job.trigger.cron this.dialogTitle = '编辑定时任务' this.showEditDialog = true }, saveJob() { if (this.job.id == null) { axios.post('/api/jobs', this.job) .then(response => { this.getJobs() this.showEditDialog = false }) .catch(error => { console.log(error) }) } else { axios.put('/api/jobs/' + this.job.id, this.job) .then(response => { this.getJobs() this.showEditDialog = false }) .catch(error => { console.log(error) }) } }, deleteJob(job) { axios.delete('/api/jobs/' + job.id) .then(response => { this.getJobs() }) .catch(error => { console.log(error) }) }, closeDialog() { this.showEditDialog = false } } } </script> ``` 在这里,我们使用了 axios 库来向后端发送 HTTP 请求,并且使用了 v-for 和 v-model 指令来实现页面数据的绑定和循环展示。 4. 在后端使用 SpringBootQuartz,创建一个 RESTful API,用于接收前端页面发送的添加、修改和删除定时任务的请求。具体实现可以参考以下代码: ``` @RestController @RequestMapping("/api/jobs") public class JobController { @Autowired private Scheduler scheduler; @GetMapping("") public List<JobDetail> getAllJobs() throws SchedulerException { List<JobDetail> jobs = new ArrayList<>(); for (String groupName : scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { JobDetail jobDetail = scheduler.getJobDetail(jobKey); jobs.add(jobDetail); } } return jobs; } @PostMapping("") public void addJob(@RequestBody JobDetail jobDetail) throws SchedulerException { JobDataMap jobDataMap = jobDetail.getJobDataMap(); String jobName = jobDataMap.getString("jobName"); String jobGroup = jobDataMap.getString("jobGroup"); String jobClass = jobDataMap.getString("jobClass"); String cronExpression = jobDataMap.getString("cronExpression"); JobDetail newJob = JobBuilder.newJob() .withIdentity(jobName, jobGroup) .ofType((Class<? extends Job>) Class.forName(jobClass)) .build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(jobName + "Trigger", jobGroup) .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)) .build(); scheduler.scheduleJob(newJob, trigger); } @PutMapping("/{id}") public void updateJob(@PathVariable("id") String id, @RequestBody JobDetail jobDetail) throws SchedulerException { JobDataMap jobDataMap = jobDetail.getJobDataMap(); String jobName = jobDataMap.getString("jobName"); String jobGroup = jobDataMap.getString("jobGroup"); String jobClass = jobDataMap.getString("jobClass"); String cronExpression = jobDataMap.getString("cronExpression"); JobKey jobKey = new JobKey(jobName, jobGroup); JobDetail oldJob = scheduler.getJobDetail(jobKey); JobDetail newJob = JobBuilder.newJob() .withIdentity(jobName, jobGroup) .ofType((Class<? extends Job>) Class.forName(jobClass)) .build(); newJob.getJobDataMap().putAll(oldJob.getJobDataMap()); TriggerKey triggerKey = new TriggerKey(jobName + "Trigger", jobGroup); Trigger oldTrigger = scheduler.getTrigger(triggerKey); Trigger newTrigger = TriggerBuilder.newTrigger() .withIdentity(jobName + "Trigger", jobGroup) .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)) .build(); scheduler.scheduleJob(newJob, newTrigger); } @DeleteMapping("/{id}") public void deleteJob(@PathVariable("id") String id) throws SchedulerException { String[] ids = id.split(":"); String jobName = ids[0]; String jobGroup = ids[1]; JobKey jobKey = new JobKey(jobName, jobGroup); scheduler.deleteJob(jobKey); } } ``` 在这里,我们使用了 Quartz 的 Scheduler 接口来动态创建、修改和删除定时任务,并且使用了 @RequestBody、@PostMapping、@PutMapping 和 @DeleteMapping 注解来接收前端页面发送的请求。 5. 最后,在 SpringBoot 应用程序的配置文件中,添加 Quartz 的相关配置,如下所示: ``` quartz: job-store-type: memory properties: org: quartz: scheduler: instanceName: myScheduler instanceId: AUTO jobFactory: class: org.springframework.scheduling.quartz.SpringBeanJobFactory jobStore: class: org.quartz.simpl.RAMJobStore threadPool: class: org.quartz.simpl.SimpleThreadPool threadCount: 10 threadPriority: 5 threadsInheritContextClassLoaderOfInitializingThread: true ``` 在这里,我们设置了 Quartz 的存储类型为内存存储,以及一些基本的配置项,如线程池大小和线程优先级等。 以上就是动态定时任务的实现步骤,希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值