java|(微信定时发送消息)一个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 resource = getResouce(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //遍历某个时间段需要做的事情 for (String todo : resource) { String[] item = todo.split(" "); String formatData = https://www.it610.com/article/year+"-"+month+"-"+day+" "+item[0]+":00"; Date firstData = https://www.it610.com/article/simpleDateFormat.parse(formatData); List> sendData = https://www.it610.com/article/new ArrayList<>(); String[] sends = todo.split("; "); int i = 0; for (String send : sends) { Map map = new HashMap<>(); List strings = Arrays.asList(send.split(" ")); if (i==0){ map.put("receive",strings.get(1)); map.put("content",strings.get(2)); }else { map.put("receive",strings.get(0)); map.put("content",strings.get(1)); } sendData.add(map); i++; } createTask(firstData,sendData); } }private static int queryProcessCount(String processName) throws IOException { int count = 0; Runtime runtime = Runtime.getRuntime(); List tasklist = new ArrayList<>(); Process process = runtime.exec("tasklist"); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String s; while ((s = br.readLine()) != null) { if ("".equals(s)) { continue; } tasklist.add(s); } for (String taskName : tasklist) { if (taskName.contains(processName)){ count++; } } return count; } private static void createTask(Date firstData,List> sendData){ if (firstData.getTime()-System.currentTimeMillis()<0){ //让错过的时间延后配置的间隔时间执行 firstData = https://www.it610.com/article/new Date(firstData.getTime()+SECTION); } new Timer().scheduleAtFixedRate(new java.util.TimerTask() { @Override public synchronized void run() { try { openWeChat(); for (Map sendDatum : sendData) { sendMsg(sendDatum.get("receive"),sendDatum.get("content")); Thread.sleep(500); } closeWeChat(); } catch (Exception e) { e.printStackTrace(); } } },firstData.getTime() - System.currentTimeMillis(),SECTION); }public static void setSysClipboardFile(String imageUrl) throws IOException { Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); if (imageUrl.contains("\\")){ imageUrl = imageUrl.replace("\\","/"); } imageUrl = imageUrl.replace("img(",""); imageUrl = imageUrl.substring(0, imageUrl.length() - 1); Image image = ImageIO.read(new File(imageUrl)); Transferable trans = new Transferable() { @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (isDataFlavorSupported(flavor)) { return image; } throw new UnsupportedFlavorException(flavor); }@Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.imageFlavor }; }@Override public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } }; clip.setContents(trans, null); }public static void setSysClipboardText(String writeMe) { Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable tText = new StringSelection(writeMe); clip.setContents(tText, null); }private static void openWeChat() throws AWTException { Robot robot = RobotManager.getInstance(); //robot.keyPress(KeyEvent.VK_WINDOWS); //robot.keyPress(KeyEvent.VK_D); //robot.keyRelease(KeyEvent.VK_WINDOWS); //robot.keyRelease(KeyEvent.VK_D); //先使用win+D快捷键保证微信为最小化状态,再使用微信默认快捷键打开微信nihao2 robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_W); robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyRelease(KeyEvent.VK_ALT); robot.keyRelease(KeyEvent.VK_W); robot.delay(100); }/** * 发送消息 * @param receive 接收消息者 * @param msg 消息内容 */ private static void sendMsg(String receive,String msg) throws Exception { Robot robot = RobotManager.getInstance(); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_F); robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyRelease(KeyEvent.VK_F); inputEnter(receive); inputEnter(msg); }private static void closeWeChat() throws AWTException { Robot robot = RobotManager.getInstance(); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_W); robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyRelease(KeyEvent.VK_ALT); robot.keyRelease(KeyEvent.VK_W); }private static void inputEnter(String msg) throws Exception { Robot robot = RobotManager.getInstance(); if (msg.contains("img(")){ setSysClipboardFile(msg); }else { setSysClipboardText(msg); } robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyRelease(KeyEvent.VK_V); robot.delay(1000); robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); robot.delay(500); }public static class RobotManager{ private static Robot robot; public static Robot getInstance() throws AWTException { if (robot==null){ robot = new Robot(); } return robot; } }public static List getResouce() throws Exception { StringBuilder result = new StringBuilder(); //读取桌面Txt文件,桌面路径与文件名根据需要修改 FileReader reader = new FileReader("C:\\Users\\xjt\\Desktop\\sendmag.txt", StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(reader); String temp; while((temp = br.readLine())!=null){//使用readLine方法,一次读一行 result.append(temp); } br.close(); reader.close(); return Arrays.asList(result.toString().split("\\*")); } }

配置信息 需要用到的桌面文本文件配置信息内容
11:14 接收者名称 发送内容; xjt(接收者名称) img(C:\Users\Hasee\Desktop\checkcode.jpg); 文件传输助手 内容* 11:15 xjt nihao2* 11:16 xjt nihao3

配置文件分析 配置符号由代码中定义。可根据需要进行修改优化
*:当前时间运行任务结束符,最后一个任务不需要结束符
; :每个任务的间隔符
空格:时间与接受者名称与内容的分隔符
img():当内容为图片时指定的图片本地绝对地址
使用方式
  1. 复制上述代码内容为一个名为TimerTask.java文件
  2. 修改文件中,当前环境配置文件指定地址
java|(微信定时发送消息)一个java文件,完成可配置的微信定时任务
文章图片

执行编译运行命令
编译
javac -encoding UTF-8 TimerTask.java

开始运行
java TimerTask

【java|(微信定时发送消息)一个java文件,完成可配置的微信定时任务】或者直接在ide开发工具中运行

    推荐阅读