栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring节假日定时发送阿里短信任务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring节假日定时发送阿里短信任务

需求:节假日发送短信祝福比如

祝您元旦快乐,心想事成,幸福永驻,快乐永随!

短信接口调用阿里大于  签名,模版编号

入依赖(去阿里官网看)

代码机构:

xml-mapper-service-serviceimp-

SmsUtil阿里短信接口
package com.yilingxinxi.common.utils;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import org.springframework.scheduling.annotation.EnableScheduling;


import org.springframework.stereotype.Component;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.linkedHashMap;
import java.util.Map;
import java.util.Random;

@Component
public class SmsUtils {

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    private final String accessKeyId = AliyunMsgConf.ACCESSKEYID;

    private final String accessKeySecret = AliyunMsgConf.ACCESSKEYSECTRET;


    public SendSmsResponse sendSms(String phoneNumbers, String signName, String templateCode, String param) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.clientc .defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNumbers);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(param);

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");

        //hint 此处可能会抛出异常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }

    // 根据成长 bizID 获取当前消息详细状态(一般不用)
    public QuerySendDetailsResponse querySendDetails(String bizId, String phoneNumber) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(phoneNumber);
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询,格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常,注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

    // 测试工具类
    public static void main(String[] args) throws ClientException {
        SmsUtils smsUtils = new SmsUtils();
        try {
            Random r = new Random();
            int code = r.nextInt(899999) + 100000;


            SendSmsResponse sendSmsResponse = smsUtils.sendSms("测试手机号", "短信开头", "模版编号", "{"code":"" + code + ""}" );


            System.out.println(sendSmsResponse.toString());
        } catch (ClientException e) {
            e.printStackTrace();

        }
    }

}
 

节假日数组HolidayFactory
package com.yilingxinxi.weapp.job;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@Component
public class HolidayFactory {

    private final Map holidays = new HashMap<>(16);

    public HolidayFactory() {
        this.holidays.put("国庆节", "你的节日模版编号");
        this.holidays.put("劳动节", "你的节日模版编号");
        this.holidays.put("儿童节", "你的节日模版编号");
        this.holidays.put("中秋节", "你的节日模版编号");
        this.holidays.put("教师节", "你的节日模版编号");
        this.holidays.put("元宵节", "你的节日模版编号");
        this.holidays.put("春节", "你的节日模版编号");
        this.holidays.put("元旦", "你的节日模版编号");
        this.holidays.put("测试节日", "你的节日模版编号");
    }

    public String getHolidaySmsTemplate(String holidayName) {
        return this.holidays.get(holidayName);
    }

定时器代码

package com.yilingxinxi.weapp.job;

import com.aliyuncs.exceptions.ClientException;
import com.yilingxinxi.common.utils.SmsUtils;
import com.yilingxinxi.model.Child;
import com.yilingxinxi.model.Holiday;
import com.yilingxinxi.model.Teacher;
import com.yilingxinxi.service.service.ChildService;
import com.yilingxinxi.service.service.HolidayService;
import com.yilingxinxi.service.service.TeacherService;
import org.apache.axis.types.Id;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;



@Component
@EnableScheduling
public class HolidaySms {

    private final Logger logger = LoggerFactory.getLogger(HolidaySms.class);

    @Autowired
    private HolidayService holidayService;
    @Autowired
    private ChildService childService;
    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private HolidayFactory holidayFactory;

    //    @Scheduled(cron = "0 30 8 ? * * ")//定时器
    @Scheduled(cron = "0 */1 * * * ?")
    public void holidayGreetings() throws ClientException {
        List holidays = holidayService.findHoliday();
        if (!holidays.isEmpty()) {
            String holidayName = holidays.get(0).getName();
            int count = childService.count();//.count()是定义查询学员表中的人数的
            int step = 5;
            int times;
            if (count % step == 0) {
                times = count / step;
            } else {
                times = count / step + 1;
            }
            for (int i = 0; i < times; i++) {
                List children = childService.getChildByPage(i * step, step);
                for (Child child : children) {
                    String holidaySmsTemplate = holidayFactory.getHolidaySmsTemplate(holidayName);
                    logger.info("****祝您国庆节快乐,山河壮丽,岁月峥嵘;江山不老,祖国常春!{}", holidaySmsTemplate);
//                    smsUtils.sendSms(child.getPhoneNumber(), "短信开头",holidayFactory.get(holidayName) , null);
                }
            }
            logger.info("短信发送成功");
        }

    }

}

附带一个过生日的
package com.yilingxinxi.weapp.job;

import com.aliyuncs.exceptions.ClientException;
import com.yilingxinxi.common.utils.SmsUtils;
import com.yilingxinxi.model.Child;
import com.yilingxinxi.model.Holiday;
import com.yilingxinxi.service.service.ChildService;
import com.yilingxinxi.service.service.HolidayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@EnableScheduling
public class bitdaySms {
    private final Logger logger = LoggerFactory.getLogger(HolidaySms.class);

    @Autowired
    private ChildService childService;
    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private HolidayFactory holidayFactory;

    @Scheduled(cron = "0 */1 * * * ?")
    public void bitdayGreetings() throws ClientException {
        //获取今天过生日的人的电话
        List strings = childService.selectbithday();
        //遍历发送
        for (String string : strings) {
            logger.info(string + "happy birthday");
//            smsUtils.sendSms(string, "短信开头", "你的短信模编号", null);
        }

    }
}

*注意 本人是用sql在数据库对比时间获取日期为当天的手机号(不建议,虽然方便直接用@select 记得格式化数据库时间  )

list<>也要主意返回的参数

我的节假日日学员电话要便利可以根据总人数来i++遍历

@Select("selectn+" +
            "tphone_numbern" +
            " from n" +
            "tlx_child where DATE_FORMAT(NOW(), '%Y-%m-%d') = DATE_FORMAT( FROM_UNIXTIME( lx_child.birthday / 1000) ,'%Y-%m-%d')")
    List selectbithday();

定时任务器

使用spring @Scheduled注解执行定时任务、_sd4000784的专栏-CSDN博客_@scheduled注解可以看看这个

如果你用jdk8处理时间可以看看

Java8 日期时间处理_日拱一卒-CSDN博客_java8 时间

idea快捷键

史上最全的IDEA快捷键总结_扬帆向海的博客-CSDN博客_idea全选快捷键

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/274505.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号