quartz,TimedTask,定时任务编写(不包含集群),微信模板消息

 项目目录结构

bean>AjaxMessage.java

import com.qianfeng.openapi.wechatpublicaccount.pojo.Application;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.List;

/**
 * 前端页面用到的所有ajax返回结果统一封装
 */
@Setter
@Getter
@NoArgsConstructor
public class AjaxMessage<T> extends Application {
    private boolean status;
    private String message;
    private Object result;
    private Object[] resultSet;
    private long count;
    private List<T> data;

    public AjaxMessage(long count, List<T> data) {
        this.count = count;
        this.data = data;
    }

    public AjaxMessage(Boolean status, String message) {
        this.status = status;
        this.message = message;
    }

    public AjaxMessage(boolean status1, String message, Application result) {
        this.status = status1;
        this.message = message;
        this.result = result;
    }

    public AjaxMessage(boolean status1, String message, Object[] resultSet) {
        this.status = status1;
        this.message = message;
        this.resultSet=resultSet;
    }

    public AjaxMessage(boolean status1, String message, Object result, Object[] resultSet) {
        this.status = status1;
        this.message = message;
        this.result = result;
        this.resultSet = resultSet;
    }

    @Override
    public String toString() {
        return "AjaxMessage{" +
                "status=" + status +
                ", message='" + message + '\'' +
                ", result=" + result +
                ", resultSet=" + resultSet.toString() +
                '}';
    }
}

bean>DataBean.java

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

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

@Setter
@Getter
@NoArgsConstructor
@ToString
public class DataBean {
    private static final long serialVersionUID = 1L;

    {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        date=dateString;
    }

    /**内容*/
    private String date;

     private String value;
    /**字体颜色*/
     private String color;

    public DataBean(String value, String color) {
        this.value = value;
        this.color = color;
    }

    public DataBean(String date, String value, String color) {
        this.date = date;
        this.value = value;
        this.color = color;
    }
}

bean>JobDetailBean.java

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import top.jfunc.json.annotation.DateFormat;

import java.util.Date;


@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class JobDetailBean {
    /**工作名*/
    private String jobName;
    /**工作组*/
    private String jobGroup;
    /**工作发生时间*/
    @DateFormat("yyyy-MM-dd HH:mm:ss")
    private Date jobDate;
    /**工作条数*/
    private int jobTotal;

}

bean>TableData.java

import lombok.Data;

import java.util.List;

/**
 * @author
 */
@Data
public class TableData<T> {
    private int code=0;
    private String msg;
    private long count;
    private List<T> data;

    public TableData() {
    }

    public TableData(long count, List<T> data) {
        this.count = count;
        this.data = data;
    }
}

*config>JobFactory.java

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;


@Component
public  class JobFactory extends AdaptableJobFactory {

    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;


    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        // 进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

*config>QuartzConfiguration.java

import org.quartz.Scheduler;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;


@Configuration
public class QuartzConfiguration {
    @Autowired
    private JobFactory jobFactory;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(jobFactory);
        // 用于quartz集群,QuartzScheduler 启动时更新己存在的Job
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        //延长启动
        schedulerFactoryBean.setStartupDelay(1);
        //设置加载的配置文件
        schedulerFactoryBean.setConfigLocation(new ClassPathResource("/application.yml"));
        return schedulerFactoryBean;
    }

    @Bean
    public Scheduler scheduler() {
        return schedulerFactoryBean().getScheduler();
    }
}

controller>TimedInfoController.java

import com.github.pagehelper.PageInfo;
import com.qianfeng.openapi.wechatpublicaccount.bean.AjaxMessage;
import com.qianfeng.openapi.wechatpublicaccount.bean.TableData;
import com.qianfeng.openapi.wechatpublicaccount.pojo.Application;
import com.qianfeng.openapi.wechatpublicaccount.service.TimedInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/sys/table")
@CrossOrigin(origins = "http://localhost:8080")//浏览器的同源策略,设置允许访问
public class TimedInfoController{

    @Autowired
    private TimedInfoService timedInfoService;

    @RequestMapping("/add")
    public AjaxMessage add(Application application) {
        try {
            timedInfoService.addTimedTask(application);
            return new AjaxMessage(true, "添加成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return new AjaxMessage(true, "添加失败",application);
    }

    @RequestMapping("/deleteIds")
    public AjaxMessage delete(int[] ids) {
        try {
            timedInfoService.deleteByIds(ids);
            return new AjaxMessage(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "删除失败");
    }

    @RequestMapping("/deleteId")
    public AjaxMessage delete(String groupId) {
        try {
            timedInfoService.deleteByGroupId(groupId);
            return new AjaxMessage(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "删除失败");
    }

    @RequestMapping("/update")
    public AjaxMessage update(Application application) {
        try {

            timedInfoService.updateTimedTask(application);
            return new AjaxMessage(true, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "更新失败");
    }

    @RequestMapping("/getById")
    public AjaxMessage getById( String groupId) {
        try {

            Application info = timedInfoService.getTimedTaskByGgroupId(groupId);
            return new AjaxMessage(true, "查询成功",info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "查询失败");

    }

    @RequestMapping("/getByGroup")
    public Application getById(int id) {
        try {

            Application info = timedInfoService.getTimedTaskById(id);
            return new AjaxMessage(true, "查询成功",info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "查询失败");

    }

    @RequestMapping("/getAll")//获取所有客户列表,添加应用时使用,实际开发中不需要
    public TableData getAll(Application application,  Integer page,  Integer limit) {
        try {
            PageInfo<Application> pageInfo=timedInfoService.getAllTimed(application,page,limit);
            return new TableData(pageInfo.getTotal(),pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }








    @RequestMapping("/getAdminUsers")
    public AjaxMessage getAdminUsers() {
        try {
            Object[] info = timedInfoService.getAdminUsers();
            return new AjaxMessage(true, "查询成功",null,info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "查询失败",null,null);

    }


}

controller>TimedTaskController.java

import com.qianfeng.openapi.wechatpublicaccount.bean.AjaxMessage;
import com.qianfeng.openapi.wechatpublicaccount.pojo.Application;
import com.qianfeng.openapi.wechatpublicaccount.service.TimedTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sys/timedTask")
@CrossOrigin(origins = "http://localhost:8080")//浏览器的同源策略,设置允许访问
public class TimedTaskController {

    @Autowired
    private TimedTaskService timedTaskService;

    @RequestMapping("/addStart")
    public AjaxMessage startTimedTask(Application application) {
        try {
            Application info = timedTaskService.startTimedTask(application);
            return new AjaxMessage(true, "添加成功",info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "添加失败",application);
    }

    @RequestMapping("/pause")
    public AjaxMessage pauseTimedTask (String groupId) {
        try {
            timedTaskService.pauseTimedTaskAll(groupId);
            return new AjaxMessage(true, "暂停成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "暂停失败");
    }

    @RequestMapping("/recover")
    public AjaxMessage recoverTimedTask( String groupId) {
        try {
            timedTaskService.recoverTimedTaskAll(groupId);
            return new AjaxMessage(true, "暂停成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "暂停失败");
    }

    @RequestMapping("/delete")
    public AjaxMessage deleteTimedTask( String jobName, String groupId) {
        try {
            timedTaskService.deleteTimedTask(jobName,groupId);
            return new AjaxMessage(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "删除失败");
    }

    @RequestMapping("/updata")
    public AjaxMessage updataTimedTask(Application application) {
        try {
            timedTaskService.updataTimedTask(application);
            return new AjaxMessage(true, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxMessage(false, "更新失败");
    }

}

mapper>TimedInfoMapper.java

import com.qianfeng.openapi.wechatpublicaccount.pojo.Application;

import java.util.List;


public interface TimedInfoMapper {

    void addTimedTask(Application application);

    Application getTimedTaskById(int id);

    List<Application> getAllTimed();

    void updateTimedTask(Application application);

    void deleteByIds(int[] ids);

    void deleteByGroupId(String groupId);

    Application getTimedTaskByGroupId(String groupId);

    Object[] getAdminUsers();
}

pojo>AdminUser.java

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

@Data
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class AdminUser {
    private Integer id;
    private String password;
    private String email;
    private String realName;
    private Integer status;
    private String openId;

}

pojo>Application.java

import com.fasterxml.jackson.annotation.JsonInclude;
import com.qianfeng.openapi.wechatpublicaccount.service.TimedInfoService;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class Application implements Cloneable, Serializable {
  private static final long serialVersionUID = 1586034423739L;

  /**
   * 消息ID
   */
  private String id;

  /**
   * 定时任务状态(1开启 0关闭)
   */
  private int status = 0;

  /**
   * 分组Id
   */
  private String groupId = "group2";

  /**
   * 触发器key
   */
  private String triggerName = "trigger2";

  /**
   * cron表达式
   */
  private String cron = "*/3 * * * * ?";

  /**
   * 执行体key
   */
  private String jobName = "job2";

  /**
   * access_token 运行时获取
   */
  private String token;

  /**
   * 模板id
   */
  private String templateId= "xxxxx";

  /**
   * 公众号密钥
   */
  private String secret = "xxxxxx";

  /**
   * 公众号的应用ID
   */
  private String appid = "xxxx";

  /**
   * 授予形式
   */
  private String grantType = "client_credential";

  /**
   * 消息总条数
   */
  private int jobTotal;

  /**
   * 消息标题
   */
  private String first = "申请成功XXX";

  /**
   * 消息正文
   */
  private String keyword1 = "私有化部署XXX";

  /**
   * 消息正文
   */
  private String keyword2 = "私有化部署XXX2";

  /**
   * 消息发送时间
   */
  private java.sql.Timestamp date;

  /**
   * 备注
   */
  private String remark = "申请成功XXX";

  /**
   * 消息文本颜色
   */
  private String color = "#173177";

  /**
   * 数据库引用的结果集
   */
  private Application application;

  @Override
  public Object clone() throws CloneNotSupportedException {
    Application application = null;
    try {
      application = (Application) super.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    return application;
  }

}

service>TimedInfoService.java

import com.github.pagehelper.PageInfo;
import com.qianfeng.openapi.wechatpublicaccount.pojo.Application;

public interface TimedInfoService {

    void addTimedTask(Application application);

    void deleteByIds(int[] ids);

    void deleteByGroupId(String groupId);

    Application getTimedTaskById(int id);

    Application getTimedTaskByGgroupId(String groupId);

    PageInfo<Application> getAllTimed(Application application,Integer page, Integer limit);

    void updateTimedTask(Application application);

    Object[] getAdminUsers();
}

service>TimedTaskService.java

import com.qianfeng.openapi.wechatpublicaccount.pojo.Application;


public interface TimedTaskService {
    /**启动定时任务*/
    Application startTimedTask(Application application)throws Exception;

    /**暂停定时任务*/
    void pauseTimedTaskAll(String groupId)throws Exception;

    /**恢复暂停的定时任务*/
    void recoverTimedTaskAll(String groupId)throws Exception;

    /**删除定时任务*/
    void deleteTimedTask(String jobName,String groupId)throws Exception;

    /**更新数据*/
    void updataTimedTask(Application application)throws Exception;
}

service>impl>TimedInfoServiceImpl.java

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.openapi.wechatpublicaccount.mapper.TimedInfoMapper;
import com.qianfeng.openapi.wechatpublicaccount.pojo.Application;
import com.qianfeng.openapi.wechatpublicaccount.service.TimedInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class TimedInfoServiceImpl implements TimedInfoService {
    @Autowired(required = false)
    private TimedInfoMapper timedInfoMapper;

    @Override
    public void addTimedTask(Application application) {
        timedInfoMapper.addTimedTask(application);
    }

    @Override
    public void deleteByIds(int[] ids) {
        if (ids == null || ids.length == 0) {
            return;
        }
        for (int id : ids) {
            Application application = timedInfoMapper.getTimedTaskById(id);
            if (application != null) {
                timedInfoMapper.deleteByIds(ids);
                timedInfoMapper.updateTimedTask(application);
            }
        }
    }
    @Override
    public void deleteByGroupId(String groupId) {
        timedInfoMapper.deleteByGroupId(groupId);
    }

    @Override
    public Application getTimedTaskById(int id) {
        return timedInfoMapper.getTimedTaskById(id);
    }

    @Override
    public Application getTimedTaskByGgroupId(String groupId) {
        return timedInfoMapper.getTimedTaskByGroupId(groupId);
    }

    @Override
    public PageInfo<Application> getAllTimed(Application application,Integer page, Integer limit) {
        PageHelper.startPage(page,limit);
        return new PageInfo<>(timedInfoMapper.getAllTimed());
    }

    @Override
    public void updateTimedTask(Application application) {
        timedInfoMapper.updateTimedTask(application);
    }

    @Override
    public Object[] getAdminUsers() {
        return timedInfoMapper.getAdminUsers();
    }


}

service>impl>TimedTaskServiceImpl.java

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qianfeng.openapi.wechatpublicaccount.bean.DataBean;
import com.qianfeng.openapi.wechatpublicaccount.pojo.AdminUser;
import com.qianfeng.openapi.wechatpublicaccount.pojo.Application;
import com.qianfeng.openapi.wechatpublicaccount.service.TimedInfoService;
import com.qianfeng.openapi.wechatpublicaccount.service.TimedTaskService;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
@Transactional
public class TimedTaskServiceImpl implements TimedTaskService ,Job{
    private int jobTotal=0;
    /**数据库操作的映射文件*/
    @Autowired
    private TimedInfoService timedInfoService;
    @Autowired
    private Scheduler scheduler;
    //@Autowired(required = false)
   //private Application application;

    /**启动定时任务*/
    @Override
    public Application startTimedTask(Application application) throws Exception{
        Scheduler scheduler= new StdSchedulerFactory().getScheduler();
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(application.getTriggerName(), application.getGroupId())
                .withSchedule(CronScheduleBuilder.cronSchedule(application.getCron()))
                .build();
        //3,JobDetail(工作详情)
        JobDetail jobDetail= JobBuilder.newJob(TimedTaskServiceImpl.class).withIdentity(application.getJobName(),application.getGroupId()).build();

        //6,只执行一次,获取第一次token值
        String token = getToken(application);
        //7,将获取到的token值以及存入application对象
        application.setToken(token);
        //状态改变
        application.setStatus(1);
        //8,将数据存入数据库
        timedInfoService.addTimedTask(application);
        //获取数据库中存储的参数
        Application info = timedInfoService.getTimedTaskByGgroupId(application.getGroupId());
        //获取接收消息的用户列表
        Object[] toUsers=timedInfoService.getAdminUsers();
        //PageInfo<AdminUser> toUsers=adminUserService.getUserList(new AdminUser(),1,10);
        //向jobDetail中存入数据方便execute取值
        jobDetail.getJobDataMap().put("Application",info);
        jobDetail.getJobDataMap().put("ToUsers",toUsers);
        jobDetail.getJobDataMap().put("TimedInfoService",timedInfoService );
        //4,将JobDetail和触发器增加到调度器中 scheduleJob(调度作业)
        scheduler.scheduleJob(jobDetail,trigger);
        //5,启动,调度器开始工作
        scheduler.start();

        return info;
    }

    /**获取token */
    public String getToken(Application application){
       try {
           // 接口地址拼接参数
           String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + application.getGrantType() + "&appid=" + application.getAppid()+ "&secret=" + application.getSecret();
           String tokenJsonStr = doGetPost(getTokenApi, "GET", null);
           JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
           String token = tokenJson.get("access_token").toString();
           System.out.println("获取到的TOKEN : " + token);
           //将token值存入
           application.setToken(token);
           //得到所需数据后将数据存入数据库
           timedInfoService.updateTimedTask(application);
           return token;
       }catch (Exception e){
           System.err.println("获取token失败!请检查网络或数据库参数是否为空");
           e.printStackTrace();
       }
       return null;
    }

    /**定时任务执行体*/
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        JobKey key = jobDetail.getKey();
        Application info = (Application) jobDetail.getJobDataMap().get("Application");
        if (jobTotal!=0&&info.getStatus()==1) {
            try {
                SendWeChatMsg(info, jobDetail);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        jobTotal++;
        System.err.println("打印日志:" + key.getName() + "  " + key.getGroup());
        System.out.println("hello job exec. [Time:" + new Date() + "]");

    }

    /**发送消息*/
    public Application SendWeChatMsg(Application application,JobDetail jobDetail) throws Exception{
        Object[] toUsers= (Object[]) jobDetail.getJobDataMap().get("ToUsers");

        System.err.println("即将发送消息。。。。。");
        for (int i = 0; i < toUsers.length; i++) {
            AdminUser touser= (AdminUser) toUsers[i];
            System.err.println("向第"+i+"个用户对象发送消息:"+touser);

            //TODO tokem值时效120分钟
            // 接口地址
            String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + application.getToken();
            //整体参数map
            Map<String, Object> paramMap = new HashMap<String, Object>();
            //消息主题显示相关map
            Map<String, Object> dataMap = new HashMap<String, Object>();
            //根据自己的模板定义内容和颜色
            DataBean dataBean = new DataBean();
            System.err.println(dataBean.getDate());
            dataMap.put("first", new DataBean(application.getFirst(), application.getColor()));
            dataMap.put("keyword1", new DataBean(application.getKeyword1(), application.getColor()));
            dataMap.put("keyword2", new DataBean(dataBean.getDate(), application.getColor()));
            dataMap.put("remark", new DataBean(application.getRemark(), application.getColor()));
            paramMap.put("touser", touser.getOpenId());
            paramMap.put("template_id", application.getTemplateId());
            paramMap.put("data", dataMap);
            System.out.println(doGetPost(sendMsgApi, "POST", paramMap));

            System.err.println("消息发送成功");
        }

        return application;
    }

    /** 调用接口 post*/
    public String doGetPost(String apiPath, String type, Map<String,Object> paramMap)throws Exception{
        OutputStreamWriter out = null;
        InputStream is = null;
        String result = null;
        try{
            // 创建连接
            URL url = new URL(apiPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod(type) ;
            // 设置接收数据的格式
            connection.setRequestProperty("Accept", "application/json");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            if(type.equals("POST")){
                // utf-8编码
                out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                out.append(JSON.toJSONString(paramMap));
                out.flush();
                out.close();
            }
            // 读取响应
            is = connection.getInputStream();
            // 获取长度
            int length = (int) connection.getContentLength();
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                // utf-8编码
                result = new String(data, "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }

    /**
     * 暂停组内所有定时任务
     */
    @Override
    public void pauseTimedTaskAll(String groupId) throws Exception{
        //1,调度器Scheduler
        Scheduler scheduler= StdSchedulerFactory.getDefaultScheduler();
        System.err.println("准备暂停...");
        scheduler.pauseJobs(GroupMatcher.groupEquals(groupId));
        System.err.println("暂停成功");
    }
    /**
     * 恢复组内所有定时任务
     */
    @Override
    public void recoverTimedTaskAll(String groupId) throws Exception{
        //1,调度器Scheduler
        Scheduler scheduler= StdSchedulerFactory.getDefaultScheduler();
        System.err.println("准备恢复...");
        scheduler.resumeJobs(GroupMatcher.groupEquals(groupId));
        System.err.println("恢复成功");
    }
    /**
     * 恢复组内所有定时任务
     */
    @Override
    public void deleteTimedTask(String jobName ,String jobGroup) throws Exception{
        Scheduler scheduler= StdSchedulerFactory.getDefaultScheduler();
        System.err.println("准备删除...");
        // TriggerKey 定义了trigger的名称和组别 ,通过任务名和任务组名获取TriggerKey
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName,jobGroup);
        // 停止触发器
        scheduler.resumeTrigger(triggerKey);
        // 移除触发器
        scheduler.unscheduleJob(triggerKey);
        // 移除任务
        scheduler.deleteJob(JobKey.jobKey(jobName,jobGroup));
        //删除数据库中的数据
        timedInfoService.deleteByGroupId(jobGroup);

        System.err.println("删除定时任务成功");

    }

    @Override
    public void updataTimedTask(Application application) throws Exception{
        Scheduler scheduler= StdSchedulerFactory.getDefaultScheduler();
        scheduler.getJobDetail(JobKey.jobKey(application.getGroupId()));
        System.err.println("准备更新...........................................................................................");
        //获取更新之前数据库中的不需要更新的数据
        Application old=timedInfoService.getTimedTaskByGgroupId(application.getGroupId());
        //  {这里添加需要更新的数据
        application.setDate(old.getDate());
        //application.setCron("*/3 * * * * ?");

        //  }
        //删除当前任务
        deleteTimedTask(application.getJobName(),application.getGroupId());

        if (application.getStatus()==1){
            //重新启动任务(启动方法中已经包含了添加数据到数据库)
            startTimedTask(application);
        }else {
            timedInfoService.addTimedTask(application);
            pauseTimedTaskAll(application.getGroupId());
        }

        System.err.println("更新定时任务成功OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");

    }

}

WeChatStartApp.java

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement//开启事务管理
@MapperScan("com.qianfeng.openapi.wechatpublicaccount.mapper")
public class WeChatStartApp {
    public static void main(String[] args) {
        SpringApplication.run(WeChatStartApp.class,args);
    }

}

xxx.mapper>TimedInfoMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qianfeng.openapi.wechatpublicaccount.mapper.TimedInfoMapper">
    <insert id="addTimedTask" parameterType="Application" keyProperty="id">
        insert into wechat.application(id,status, groupId, triggerName, cron, jobName, token, templateId, secret, appid, grantType, jobTotal, first, keyword1,remark, color)
        VALUES (#{id},#{status},#{groupId},#{triggerName},#{cron},#{jobName},#{token},#{templateId},#{secret},#{appid},#{grantType},#{jobTotal},#{first},#{keyword1},#{remark},#{color})
    </insert>


    <select id="getTimedTaskById" parameterType="int" resultType="com.qianfeng.openapi.wechatpublicaccount.pojo.Application">
        select * from wechat.application
        where id=#{id}
    </select>
    <select id="getTimedTaskByGroupId" parameterType="String" resultType="com.qianfeng.openapi.wechatpublicaccount.pojo.Application">
        select * from wechat.application
        where groupId=#{groupId}
    </select>
    <select id="getAdminUsers" resultType="com.qianfeng.openapi.wechatpublicaccount.pojo.AdminUser">
    select * from `openapi-admin`.admin_user
    </select>

    <resultMap type="com.qianfeng.openapi.wechatpublicaccount.pojo.Application" id="ApplicationMap">
        <result property="id" column="id"/>
        <result property="status" column="status"/>
        <result property="groupId" column="groupId"/>
        <result property="triggerName" column="triggerName"/>
        <result property="cron" column="cron"/>
        <result property="jobName" column="jobName"/>
        <result property="token" column="token"/>
        <result property="templateId" column="templateId"/>
        <result property="toUser" column="toUser"/>
        <result property="secret" column="secret"/>
        <result property="appid" column="appid"/>
        <result property="grantType" column="grantType"/>
        <result property="jobTotal" column="jobTotal"/>
        <result property="first" column="first"/>
        <result property="keyword1" column="keyword1"/>
        <result property="keyword2" column="keyword2"/>
        <result property="date" column="date"/>
        <result property="remark" column="remark"/>
        <result property="color" column="color"/>
    </resultMap>
    <select id="getAllTimed" resultMap="ApplicationMap">
        select * from wechat.application
    </select>

    <delete id="deleteByIds" parameterType="int" >
        delete from wechat.application
        where id=#{id}
    </delete>
    <delete id="deleteByGroupId" parameterType="String" >
        delete from wechat.application
        where groupId=#{groupId}
    </delete>

    <update id="updateTimedTask" parameterType="com.qianfeng.openapi.wechatpublicaccount.pojo.Application">
        UPDATE wechat.application
        <set>
            <if test="status !=null and status!=''">status=#{status},</if>
            <if test="groupId !=null and groupId!=''">groupId=#{groupId},</if>
            <if test=" triggerName!=null and triggerName!=''">triggerName=#{triggerName},</if>
            <if test=" cron!=null and cron!=''">cron=#{cron},</if>
            <if test=" jobName!=null and jobName!=''">jobName=#{jobName},</if>
            <if test=" token!=null and token!=''">token=#{token},</if>
            <if test=" templateId!=null and templateId!=''">templateId=#{templateId},</if>
            <if test=" secret!=null and secret!=''">secret=#{secret},</if>
            <if test=" appid!=null and appid!=''">appid=#{appid},</if>
            <if test=" grantType!=null and grantType!=''">grantType=#{grantType},</if>
            <if test=" jobTotal!=null and jobTotal!=''">jobTotal=#{jobTotal},</if>
            <if test=" first!=null and first!=''">`first`=#{first},</if>
            <if test=" keyword1!=null and keyword1!=''">keyword1=#{keyword1},</if>
            <if test=" keyword2!=null and keyword2!=''">keyword2=#{keyword2},</if>
            <if test=" remark!=null and remark!=''">remark=#{remark},</if>
            <if test=" color!=null and color!=''">color=#{color},</if>
        </set>
        where id=#{id}
    </update>


</mapper>

resources>application.yml

server:
  port: 50000
spring:
  datasource:
    username: xxx
    password: xxx
    driver-class-name: org.gjt.mm.mysql.Driver #springboot是2.0以上建议使用
    url: jdbc:mysql://localhost:3306/wechat?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initialSize: 2
      minIdle: 2
      maxActive: 30
      #StatViewServlet:
      #loginUsername: admin
      #loginPassword: admin

#别名
  quartz:
    #相关属性配置
    properties:
      org:
        quartz:
          scheduler:
            instanceName: DefaultQuartzScheduler
            instanceId: AUTO
          jobStore:
            class: org.quartz.impl.jdbcjobstore.JobStoreTX
            driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
            tablePrefix: QRTZ_
            isClustered: false
            clusterCheckinInterval: 10000
            useProperties: true
          threadPool:
            class: org.quartz.simpl.SimpleThreadPool
            threadCount: 10
            threadPriority: 5
            threadsInheritContextClassLoaderOfInitializingThread: true
          dataSource:
            default:
              URL: jdbc:mysql://localhost:3306/wechat?characterEncoding=utf-8
              user: root
              password: 1234
              driver: com.mysql.cj.jdbc.Driver

    #数据库方式
    job-store-type: jdbc
    #初始化表结构
    #jdbc:
    #initialize-schema: never

mybatis:
  type-aliases-package: com.qianfeng.openapi.wechatpublicaccount.pojo






















 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
quartz框架是一个开源的Java调度框架,可用于编写定时任务。而Spring Boot是一个用于简化Java应用开发的框架。在将quartz框架与Spring Boot整合时,我们可以通过使用new的方式来编写定时任务。 首先,在Spring Boot的主配置类上加上@EnableScheduling注解,以启用定时任务的支持。然后,我们可以创建一个新的类并实现org.springframework.scheduling.annotation.SchedulingConfigurer接口,这个接口提供了定时任务的配置信息。在该类中,我们可以使用@Bean注解来定义一个定时任务,并设置其触发时间、逻辑等。 在定义定时任务的方法上,我们可以使用@Scheduled注解来指定任务的执行方式和触发时间。例如,可以使用@Scheduled(fixedRate = 5000)来表示每隔5秒执行一次该任务,或者使用@Scheduled(cron = "0 0 12 * * ?")来表示每天中午12点执行一次任务。 需要注意的是,在使用new的方式编写定时任务时,我们需要手动将该任务注册到quartz框架中。我们可以在Spring Boot的配置类中通过创建org.springframework.scheduling.quartz.SchedulerFactoryBean对象来获取一个Quartz调度器实例。然后,再使用调度器实例的scheduleJob方法来注册定时任务。 总的来说,通过new的方式编写定时任务的步骤如下: 1. 在Spring Boot的主配置类上加上@EnableScheduling注解,启用定时任务的支持。 2. 创建一个新的类并实现SchedulingConfigurer接口,用于配置定时任务。 3. 在配置类中定义定时任务的方法,并使用@Scheduled注解指定任务的执行方式和触发时间。 4. 在配置类中获取Quartz调度器实例,并使用调度器实例的scheduleJob方法来注册定时任务。 这样,我们就可以使用new的方式编写定时任务,并实现quartz框架与Spring Boot的整合。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

简单启明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值