(微信定时发送消息)一个java文件,完成可配置的微信定时发送消息任务

需求来源

当我们再日常工作中,需要每日定时的发送群消息,时间太早的话不想起来,想着可以用java显示定时发送消息的任务.在睡梦中让程序帮我们定时发送消息

功能介绍

定时生日祝福、每日早安、晚安问候

  1. 检测微信是否再后台运行
  2. 指定每天多个时间段发送可配置的消息
  3. 发送图片
  4. 每个时间段给多个人发送多个消息
  5. 设置间隔时间(如:两天发一次,一天发一次,每秒发一次)

代码如下

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.KeyEvent;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.*;

/**
 * @Author: xu
 * @Description: 开启定时任务,指定时间,间隔给微信好友发送文本或图片
 * @Date: 2021/12/20 20:28
 */
public class TimerTask {
   
   
//    设置定时任务区间,每隔一天发一次
    private static final Long SECTION = (long) (24 * 60 * 60 * 1000);

    public static void main(String[] args) throws Exception {
   
   
        System.out.println("任务执行时间,请保证微信在登录状态并为最小化...");
        int weChat = queryProcessCount("WeChat");
        if (weChat<=0){
   
   
            System.err.println("请登陆微信后再尝试运行");
            return;
        }
        int year = LocalDateTime.now().getYear();
        int month = LocalDateTime.now().getMonthValue();
        int day = LocalDateTime.now().getDayOfMonth();     //任务默认从今天开始
        List<String> resource = getResouce();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        遍历某个时间段需要做的事情
        for (String todo : resource) {
   
   
            String[] item = todo.split(" ");
            String formatData = year+"-"+month+"-"+day+" "+item[0]+":00";
            Date firstData = simpleDateFormat.parse(formatData);
            List<Map<String,String>> sendData = new ArrayList<>();
            String[] sends = todo.split(";");
            int i = 0;
            for (String send : sends) {
   
   
                Map<String,
### 实现Java程序通过微信定时发送消息 为了实现Java程序通过微信定时发送消息的功能,需遵循特定流程并利用相关API。此过程涉及获取`access_token`、构建待发送消息体以及设置调度器来触发定时任务。 #### 获取Access Token 由于许多高级功能请求都需要携带`access_token`作为验证参数,因此首先应从微信公众平台获得该令牌[^3]。这一步骤对于确保安全性和合法性至关重要: ```java public class WeChatUtil { private static final String APP_ID = "your_app_id"; private static final String SECRET = "your_secret"; public static String getAccessToken() throws Exception { URL url = new URL("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + SECRET); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null){ response.append(line); } JSONObject jsonResponse = new JSONObject(response.toString()); return jsonResponse.getString("access_token"); } } ``` #### 构建消息体与发送订阅消息 当拥有有效的`access_token`之后,则可以根据业务需求创建相应的消息对象,并调用微信开放平台上提供的接口完成实际的信息推送操作[^2]。下面是一个简单的例子展示如何构造一条订阅消息并向指定用户发送: ```java import org.json.JSONObject; // 假设已经获得了 access_token 并存储于变量 accessToken 中 String accessToken = WeChatUtil.getAccessToken(); public void sendSubscriptionMessage(String openId, Map<String, Object> dataMap) throws Exception{ // 订阅消息模板ID 和 接收者 openid String templateId = "TEMPLATE_ID"; // 创建 JSON 对象表示要发送的数据结构 JSONObject jsonMsgBody = new JSONObject(); jsonMsgBody.put("touser", openId); jsonMsgBody.put("template_id", templateId); // 添加具体字段内容至 msgData 字段内 JSONObject jsonData = new JSONObject(dataMap); jsonMsgBody.put("data", jsonData); // 发送 POST 请求给微信服务器 URL url = new URL("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); // 设置HTTP方法为POST和其他必要属性... conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); byte[] input = jsonMsgBody.toString().getBytes("utf-8"); os.write(input, 0, input.length); } ``` #### 定时任务配置 为了让上述逻辑能够按照预定时间间隔自动执行,可以采用Quartz这样的第三方库来进行任务调度管理。以下是基于Spring框架集成Quartz的一个基本实例说明[^1]: ```xml <!-- applicationContext.xml --> <bean id="messageJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"><ref bean="wechatService"/></property> <property name="targetMethod"><value>sendMessages</value></property> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"><ref local="messageJobDetail"/></property> <!-- 每天凌晨两点整运行一次 --> <property name="cronExpression"><value>0 0 2 * * ?</value></property> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"><list><ref bean="cronTrigger"/></list></property> </bean> ``` 以上就是关于如何使用Java实现微信定时发送消息的主要步骤和技术要点介绍。需要注意的是,在真实项目环境中还需要考虑异常处理机制、日志记录等功能模块的设计完善工作。
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

languageStudents

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

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

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

打赏作者

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

抵扣说明:

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

余额充值