自动采集

wjdr
wangbing 1 year ago
parent ce19710a0c
commit 16e4767372

@ -7,6 +7,7 @@
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="starter-jmacro" />
<module name="starter-jmacro-wjdr" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>

@ -3,7 +3,6 @@
<component name="Encoding" defaultCharsetForPropertiesFiles="UTF-8">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources/lib" charset="UTF-8" />
<file url="PROJECT" charset="UTF-8" />
</component>
</project>

@ -1,6 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />

@ -1,5 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />

Binary file not shown.

Before

Width:  |  Height:  |  Size: 398 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 570 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 678 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 700 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 696 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 679 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 758 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 595 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 743 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

@ -3,11 +3,11 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>starter-jmacro</artifactId>
<artifactId>starter-jmacro-wjdr</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<!--<packaging>war</packaging>--><!--需要打包成war时放开-->
<name>starter-jmacro</name>
<name>starter-jmacro-wjdr</name>
<description>project for Spring Boot</description>
<properties>

@ -1,40 +0,0 @@
package com.example.jmacro;
import cn.hutool.core.io.FileUtil;
import com.example.jmacro.base.ScreenRect;
import com.example.jmacro.util.Imager;
import com.example.jmacro.util.Logger;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
public class Main {
public static void main(String[] args) throws AWTException {
Logger.info("启动脚本");
Logger.info("初始化脚本...");
JMacro jMacro = new JMacro();
// 开始定位App,好让后续的图片查找限定在一定范围内提高效率如果过程中移动过App窗口需要重新定位否则无法具体部件位置
Logger.info("开始定位程序...");
List<BufferedImage> load = Imager.load(FileUtil.loopFiles(new File("legend", "main")));
ScreenRect appRect = null;
for (BufferedImage bufferedImage : load) {
appRect = jMacro.findPic(bufferedImage, 0.99d);
if (appRect != null) {
break;
}
}
if (appRect == null) {
Logger.error("定位主程序失败");
return;
}
Logger.info("定位图片成功,位置{},{},宽{},高{}", appRect.getLeft(), appRect.getTop(), appRect.getWidth(), appRect.getHeight());
// 移动鼠标
jMacro.mouseRightClick(appRect);
}
}

@ -1,15 +0,0 @@
package com.example.jmacro.util;
import cn.hutool.core.util.StrUtil;
public class Logger {
public static void info(String log, Object... arg) {
System.out.println(StrUtil.format(log, arg));
}
public static void error(String log, Object... arg) {
System.err.println(StrUtil.format(log, arg));
}
}

@ -0,0 +1,13 @@
package com.example.jmacro.wjdr;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
public abstract class JGameThread implements Runnable {
protected JMacro jMacro;
public JGameThread(JMacro jMacro) {
this.jMacro = jMacro;
}
}

@ -1,15 +1,17 @@
package com.example.jmacro;
package com.example.jmacro.wjdr;
import cn.hutool.core.util.RandomUtil;
import com.example.jmacro.base.ScreenPoint;
import com.example.jmacro.base.ScreenRect;
import com.example.jmacro.util.ColorUtil;
import com.example.jmacro.util.Imager;
import com.example.jmacro.wjdr.base.ScreenPoint;
import com.example.jmacro.wjdr.base.ScreenRect;
import com.example.jmacro.wjdr.util.ColorUtil;
import com.example.jmacro.wjdr.util.Imager;
import com.example.jmacro.wjdr.util.TaskUtil;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.TimeUnit;
/**
* Java
@ -21,18 +23,39 @@ public class JMacro {
*/
private Robot robot;
private JGameThread thread;
public JMacro() throws AWTException {
this.robot = new Robot();
}
public JGameThread getThread() {
return thread;
}
public void setThread(JGameThread thread) {
this.thread = thread;
}
/**
*
*
*
* @param point
*/
public void mouseMove(ScreenPoint point) {
waitTap();
robot.mouseMove(point.getX(), point.getY());
// 获取当前鼠标位置
Point mousePoint = MouseInfo.getPointerInfo().getLocation();
int startX = mousePoint.x;
int startY = mousePoint.y;
// 分10次移动到指定点
for (int i = 1; i <= 10; i++) {
float d = i / 10f;
int dx = (int) (startX + (point.getX() - startX) * d);
int dy = (int) (startY + (point.getY() - startY) * d);
robot.mouseMove(dx, dy);
robot.delay(RandomUtil.randomInt(30, 70));
}
}
/**
@ -41,9 +64,7 @@ public class JMacro {
* @param rect
*/
public void mouseLeftClick(ScreenRect rect) {
waitTap();
robot.mouseMove(rect.getCenter()[0], rect.getCenter()[1]);
waitTap();
mouseMove(new ScreenPoint(rect.getCenter()[0], rect.getCenter()[1]));
robot.mousePress(InputEvent.BUTTON1_MASK);
waitTap();
robot.mouseRelease(InputEvent.BUTTON1_MASK);
@ -145,7 +166,7 @@ public class JMacro {
*/
public ScreenRect findPic(ScreenRect screenRect, BufferedImage pic, double minSimilar) {
// 当查找区域比图片还小时,直接返回失败
if (screenRect.getWidth() < pic.getHeight() || screenRect.getHeight() < pic.getHeight()) {
if (screenRect.getWidth() < pic.getWidth() || screenRect.getHeight() < pic.getHeight()) {
return null;
}
@ -156,28 +177,30 @@ public class JMacro {
// 得到图片左上角范围
int xMin = screenRect.getLeft();
int xMax = screenRect.getRight() - pic.getWidth();
// 因为坐标取像素点是从0开始因此需要-1
int xMax = screenRect.getRight() - 1 - pic.getWidth();
int yMin = screenRect.getTop();
int yMax = screenRect.getBottom() - pic.getHeight();
// 因为坐标取像素点是从0开始因此需要-1
int yMax = screenRect.getBottom() - 1 - pic.getHeight();
for (int y = yMin; y <= yMax; y++) {
for (int x = xMin; x <= xMax; x++) {
// 对关键点进行先期匹配,降低运算复杂度。如果关键点本身就不匹配,就没必要再去匹配小图的每一个像素点
// 左上角
boolean lt = ColorUtil.isSimilar(screenData[x][y], picData[0][0]);
boolean lt = ColorUtil.isSimilar(screenData[x - xMin][y - yMin], picData[0][0]);
// 右上角
boolean rt = ColorUtil.isSimilar(screenData[x + pic.getWidth() - 1][y], picData[pic.getWidth() - 1][0]);
boolean rt = ColorUtil.isSimilar(screenData[x - xMin + pic.getWidth() - 1][y - yMin], picData[pic.getWidth() - 1][0]);
// 左下角
boolean lb = ColorUtil.isSimilar(screenData[x][y + pic.getHeight() - 1], picData[0][pic.getHeight() - 1]);
boolean lb = ColorUtil.isSimilar(screenData[x - xMin][y - yMin + pic.getHeight() - 1], picData[0][pic.getHeight() - 1]);
// 右下角
boolean rb = ColorUtil.isSimilar(screenData[x + pic.getWidth() - 1][y + pic.getHeight() - 1], picData[pic.getWidth() - 1][pic.getHeight() - 1]);
boolean rb = ColorUtil.isSimilar(screenData[x - xMin + pic.getWidth() - 1][y - yMin + pic.getHeight() - 1], picData[pic.getWidth() - 1][pic.getHeight() - 1]);
//中心点
boolean cc = ColorUtil.isSimilar(screenData[x + pic.getWidth() / 2][y + pic.getHeight() / 2], picData[pic.getWidth() / 2][pic.getHeight() / 2]);
boolean cc = ColorUtil.isSimilar(screenData[x - xMin + pic.getWidth() / 2][y - yMin + pic.getHeight() / 2], picData[pic.getWidth() / 2][pic.getHeight() / 2]);
if (lt && rt && lb && rb && cc) {
// 进行全像素匹配
double similar = Imager.calcSimilar(x, y, pic.getHeight(), pic.getWidth(), screenData, picData);
double similar = Imager.calcSimilar(x - xMin, y - yMin, pic.getHeight(), pic.getWidth(), screenData, picData);
if (similar >= minSimilar) {
return new ScreenRect(x, y, x + pic.getWidth(), y + pic.getHeight());
return new ScreenRect(x - xMin, y - yMin, x + pic.getWidth(), y + pic.getHeight());
}
}
}
@ -186,14 +209,36 @@ public class JMacro {
}
public void waitTap() {
robot.delay(RandomUtil.randomInt(100, 200));
int i = RandomUtil.randomInt(100, 200);
// Logger.info("随机等待{}ms", i);
robot.delay(i);
}
public void waitNormal() {
robot.delay(RandomUtil.randomInt(500, 1500));
int i = RandomUtil.randomInt(500, 1500);
// Logger.info("随机等待{}ms", i);
robot.delay(i);
}
public void waitLong() {
robot.delay(RandomUtil.randomInt(2000, 5000));
int i = RandomUtil.randomInt(2000, 5000);
// Logger.info("随机等待{}ms", i);
robot.delay(i);
}
public ScreenRect waitAndFindPic(ScreenRect rect, File file, double minSimilar) {
return waitAndFindPic(rect, file, minSimilar, 20, TimeUnit.SECONDS);
}
public ScreenRect waitAndFindPic(ScreenRect rect, File file, double minSimilar, long time, TimeUnit unit) {
return TaskUtil.timeTask(() -> {
while (true) {
waitTap();
ScreenRect pic = findPic(rect, Imager.load(file), minSimilar);
if (pic != null) {
return pic;
}
}
}, time, unit);
}
}

@ -0,0 +1,154 @@
package com.example.jmacro.wjdr;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.jmacro.wjdr.base.ScreenRect;
import com.example.jmacro.wjdr.task.TaskMining;
import com.example.jmacro.wjdr.util.Imager;
import com.example.jmacro.wjdr.util.Logger;
import com.example.jmacro.wjdr.util.TaskUtil;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws AWTException {
Logger.info("启动脚本");
Logger.setDebug(true);
boolean first = true;
Logger.info("初始化脚本...");
JMacro jMacro = new JMacro();
String workStart = "08:00:00";
String workEnd = "24:00:00";
while (true) {
ThreadUtil.sleep(1000);
// 首次启动直接执行游戏线程
if (first) {
first = false;
jMacro.setThread(new GameThread(jMacro));
TaskUtil.schedule(jMacro.getThread(), 0, TimeUnit.SECONDS);
continue;
}
if (jMacro.getThread() != null) {
// Logger.debug("待机中...");
continue;
}
if (DateUtil.isIn(DateUtil.date(), DateUtil.parse(workStart), DateUtil.parse(workEnd))) {
int anInt = RandomUtil.randomInt(5, 20);
Logger.info("等待{}分钟后,重新启动游戏线程");
jMacro.setThread(new GameThread(jMacro));
TaskUtil.schedule(jMacro.getThread(), anInt, TimeUnit.MINUTES);
}
}
}
public static class GameThread extends JGameThread {
private ScreenRect gameScreen;
public GameThread(JMacro jMacro) {
super(jMacro);
// 定位mumu bar
ScreenRect mumu = locationMuMu(jMacro);
if (mumu == null) {
throw new IllegalStateException("未检测到MuMu请开启MuMu模拟器");
}
Logger.info("游戏线程启动成功");
// 获取游戏窗口返回
gameScreen = new ScreenRect();
gameScreen.setLeft(mumu.getLeft() - 190);
gameScreen.setTop(mumu.getTop() - 7);
gameScreen.setRight(mumu.getRight() + 194);
gameScreen.setBottom(mumu.getBottom() + 950);
Logger.info("游戏窗口位置:" + gameScreen.toString());
}
@Override
public void run() {
// 获取启动图标
ScreenRect launch = jMacro.waitAndFindPic(gameScreen, new File("legend", "启动图标.png"), 0.8, 5, TimeUnit.SECONDS);
if (launch != null) {
Logger.info("启动图标坐标:", launch.toString());
Logger.info("启动程序");
jMacro.mouseLeftClick(launch);
}
Logger.info("扫描游戏主界面:");
ScreenRect = TaskUtil.timeTask(() -> {
while (true) {
ScreenRect screenRect1 = locationHome(jMacro);
if (screenRect1 != null) {
return screenRect1;
}
ThreadUtil.sleep(1000);
}
}, 30 * 1000, TimeUnit.MILLISECONDS);
if ( == null) {
jMacro.setThread(null);
Logger.info("未扫描到游戏主界:退出线程");
return;
}
Logger.info("进入游戏主界面");
Logger.info("进入任务线程");
TaskUtil.timeTask((Runnable) () -> {
while (true) {
jMacro.waitNormal();
Logger.info("检测矿场攻击状态开始");
taskMineAttack(jMacro, gameScreen);
Logger.info("检测矿场攻击状态结束");
// 自动采矿
Logger.info("自动采矿开始");
new TaskMining(jMacro, gameScreen).start();
Logger.info("自动采矿结束");
}
}, 10, TimeUnit.MINUTES);
}
}
public static ScreenRect locationHome(JMacro jMacro) {
{ // 定位弹框,关闭弹框
BufferedImage image = Imager.load(new File("legend", "首页_广告关闭按钮.png"));
ScreenRect rect = jMacro.findPic(image, 0.80d);
if (rect != null) {
jMacro.mouseLeftClick(rect);
Logger.info("检测到弹框,关闭弹框");
}
}
{ // 定位主程序
BufferedImage legend = Imager.load(new File("legend", "城镇.png"));
ScreenRect rect = jMacro.findPic(legend, 0.80d);
if (rect != null) {
Logger.info("程序主界面已就绪");
return rect;
}
}
return null;
}
public static ScreenRect locationMuMu(JMacro jMacro) {
BufferedImage image = Imager.load(new File("legend", "慕慕_工具栏.png"));
return jMacro.findPic(image, 0.99d);
}
/**
*
*/
public static void taskMineAttack(JMacro jMacro, ScreenRect screenRect) {
}
}

@ -1,4 +1,4 @@
package com.example.jmacro.base;
package com.example.jmacro.wjdr.base;
/**
*
@ -11,6 +11,10 @@ public class ScreenPoint {
public ScreenPoint() {
}
public ScreenPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;

@ -1,4 +1,4 @@
package com.example.jmacro.base;
package com.example.jmacro.wjdr.base;
/**
*
@ -63,4 +63,14 @@ public class ScreenRect {
public int[] getCenter() {
return new int[]{(left + right) / 2, (top + bottom) / 2};
}
@Override
public String toString() {
return "ScreenRect{" +
"left=" + left +
", top=" + top +
", right=" + right +
", bottom=" + bottom +
'}';
}
}

@ -0,0 +1,95 @@
package com.example.jmacro.wjdr.task;
import com.example.jmacro.wjdr.JMacro;
import com.example.jmacro.wjdr.base.ScreenRect;
import com.example.jmacro.wjdr.util.Logger;
import java.io.File;
public class TaskMining {
private JMacro jMacro;
private ScreenRect screenRect;
public TaskMining(JMacro jMacro, ScreenRect screenRect) {
this.jMacro = jMacro;
this.screenRect = screenRect;
}
public void start() {
Logger.info("自动采矿");
ScreenRect = jMacro.waitAndFindPic(screenRect, new File("legend", "城镇_野外.png"), 0.99);
if ( == null) {
Logger.error("未检测到【野外】,采矿终止");
return;
}
Logger.info("城镇_野外坐标" + .toString());
Logger.info("进入野外成功");
jMacro.mouseLeftClick();
Logger.info("定位野外按钮成功");
ScreenRect = jMacro.waitAndFindPic(screenRect, new File("legend", "野外_搜索.png"), 0.9);
jMacro.mouseLeftClick();
boolean collect = false;
while (!collect) {
}
collect("生肉", 0);
collect("木材", 0);
collect("煤矿", 0);
collect("铁矿", 0);
ScreenRect = jMacro.waitAndFindPic(screenRect, new File("legend", "城镇.png"), 0.9);
if ( == null) {
Logger.error("未检测到【城镇】,采矿终止");
return;
}
}
/**
* @param level
* @return
*/
private boolean collect(String type, int level) {
ScreenRect typeRect = jMacro.waitAndFindPic(screenRect, new File("legend", "野外_" + type + ".png"), 0.9);
jMacro.mouseLeftClick(typeRect);
if (level == 0) {
ScreenRect = jMacro.waitAndFindPic(screenRect, new File("legend", "野外_资源_-.png"), 0.98);
while ( != null) {
jMacro.waitTap();
jMacro.mouseLeftClick();
= jMacro.waitAndFindPic(screenRect, new File("legend", "野外_资源_-.png"), 0.98);
}
Logger.info("矿等级重置为1");
level = 1;
}
Logger.info("搜索{}{}级矿", type, level);
ScreenRect = jMacro.waitAndFindPic(screenRect, new File("legend", "野外_资源_搜索.png"), 0.98);
jMacro.mouseLeftClick();
ScreenRect = jMacro.waitAndFindPic(screenRect, new File("legend", "野外_资源_采集.png"), 0.98);
if ( == null) {
Logger.info("未搜索到{}{}级矿!", type, level);
ScreenRect = jMacro.waitAndFindPic(screenRect, new File("legend", "野外_资源_+.png"), 0.98);
jMacro.mouseLeftClick();
return collect(type, level + 1);
}
Logger.info("搜索到{}{}级矿", type, level);
Logger.info("采集{}{}级矿", type, level);
jMacro.mouseLeftClick();
ScreenRect = jMacro.waitAndFindPic(screenRect, new File("legend", "野外_资源_出征.png"), 0.98);
if ( == null) {
Logger.info("出征{}{}级矿失败!", type, level);
return false;
}
Logger.info("出征{}{}级矿", type, level);
jMacro.mouseLeftClick();
return true;
}
}

@ -1,4 +1,4 @@
package com.example.jmacro.util;
package com.example.jmacro.wjdr.util;
public class ColorUtil {

@ -1,4 +1,4 @@
package com.example.jmacro.util;
package com.example.jmacro.wjdr.util;
import cn.hutool.core.img.ImgUtil;

@ -0,0 +1,27 @@
package com.example.jmacro.wjdr.util;
import cn.hutool.core.util.StrUtil;
public class Logger {
private static boolean isDebug = false;
public static void setDebug(boolean isDebug) {
Logger.isDebug = isDebug;
}
public static void debug(String log, Object... arg) {
if (isDebug) {
System.out.println(StrUtil.format(log, arg));
}
}
public static void info(String log, Object... arg) {
System.out.println(StrUtil.format(log, arg));
}
public static void error(String log, Object... arg) {
System.err.println(StrUtil.format(log, arg));
}
}

@ -0,0 +1,318 @@
package com.example.jmacro.wjdr.util;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.cron.CronUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;
/**
* /
*
* @author wangbing
* @version 0.0.1
* @since 1.8
*/
public class TaskUtil extends CronUtil {
private static ScheduledExecutorService service;
public static ScheduledExecutorService getService() {
return service;
}
public static void setService(ScheduledExecutorService service) {
TaskUtil.service = service;
}
/**
* Runnable
*
* @param runnable Runnable
* @param delay (ms)
*/
public static void schedule(Runnable runnable, long delay, TimeUnit unit) {
if (service == null) {
service = new ScheduledThreadPoolExecutor(1);
}
service.schedule(runnable, delay, unit);
}
/**
* Runnable
*
* @param callable Callable
* @param delay (ms)
*/
public static <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay) {
if (service == null) {
service = new ScheduledThreadPoolExecutor(1);
}
return service.schedule(callable, delay, TimeUnit.MILLISECONDS);
}
/**
* Runnable
*
* @param callable Callable
* @param delay
* @param unit
*/
public static <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
if (service == null) {
service = new ScheduledThreadPoolExecutor(1);
}
return service.schedule(callable, delay, unit);
}
/**
* Runnable
*
* @param runnable Runnable
* @param initialDelay
* @param period -
* @param unit
*/
public static ScheduledFuture<?> scheduleAtFixedRate(Runnable runnable, long initialDelay, long period, TimeUnit unit) {
if (service == null) {
service = new ScheduledThreadPoolExecutor(1);
}
return service.scheduleAtFixedRate(runnable, initialDelay, period, unit);
}
/**
* Runnable
*
* @param runnable Runnable
* @param initialDelay
* @param period -ms
*/
public static ScheduledFuture<?> scheduleAtFixedRate(Runnable runnable, long initialDelay, long period) {
if (service == null) {
service = new ScheduledThreadPoolExecutor(1);
}
return service.scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.MILLISECONDS);
}
/**
* Runnable
*
* @param runnable Runnable
* @param initialDelay
* @param delay -
* @param unit
*/
public static ScheduledFuture<?> scheduleWithFixedDelay(Runnable runnable, long initialDelay, long delay, TimeUnit unit) {
if (service == null) {
service = new ScheduledThreadPoolExecutor(1);
}
return service.scheduleAtFixedRate(runnable, initialDelay, delay, unit);
}
/**
* Runnable
*
* @param runnable Runnable
* @param initialDelay
* @param delay -ms
*/
public static ScheduledFuture<?> scheduleWithFixedDelay(Runnable runnable, long initialDelay, long delay) {
if (service == null) {
service = new ScheduledThreadPoolExecutor(1);
}
return service.scheduleAtFixedRate(runnable, initialDelay, delay, TimeUnit.MILLISECONDS);
}
/**
* IO
*
* @param runnable
* @param maxTryCount
* @param interval
* @param <T>
*/
public static <T> T retryTask(Callable<T> runnable, int maxTryCount, long interval) {
for (int i = 0; i < maxTryCount; i++) {
T t = null;
try {
t = runnable.call();
if (t != null) {
return t;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 控制重试时间间隔
if (t == null && i < maxTryCount - 1) {
ThreadUtil.sleep(interval);
}
}
}
return null;
}
public static <T> T retryTask(Callable<T> runnable) {
return retryTask(runnable, 3, 3000);
}
public static <T> T retryTask(Callable<T> runnable, int maxTryCount) {
return retryTask(runnable, maxTryCount, 3000);
}
/**
*
*
* @param callable
* @param time
*/
public static <T> T timeTask(Callable<T> callable, long time, TimeUnit unit) {
try {
CompletionService<T> completionService = ThreadUtil.newCompletionService();
Future<T> submit = completionService.submit(callable);
return submit.get(time, unit);
} catch (Exception e) {
return null;
}
}
/**
*
*
* @param callable
* @param time
*/
public static void timeTask(Runnable callable, long time, TimeUnit unit) {
try {
CompletionService<Void> completionService = ThreadUtil.newCompletionService();
Future<Void> submit = completionService.submit(callable, null);
submit.get(time, unit);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
public static void asyncTask(Runnable runnable) {
ThreadUtil.execAsync(runnable);
}
/**
*
*/
public static <T> Future<T> asyncTask(Callable<T> callables) {
return ThreadUtil.execAsync(callables);
}
/**
* 线
*/
public static void parallelTasks(Runnable... runnables) {
Assert.notEmpty(runnables, "callable can not empty");
CompletionService<Object> completionService = ThreadUtil.newCompletionService();
for (Runnable runnable : runnables) {
completionService.submit(runnable, null);
}
}
/**
* 线
*
*/
public static Object[] parallelTasks(Callable<Object>... callables) {
Assert.notEmpty(callables, "callable can not empty");
CompletionService<Object> completionService = ThreadUtil.newCompletionService();
Object[] result = new Object[callables.length];
List<Future> futures = new ArrayList<>();
for (Callable<Object> callable : callables) {
futures.add(completionService.submit(callable));
}
try {
for (int i = 0; i < result.length; i++) {
Future<Object> take = completionService.take();
int indexOf = futures.indexOf(take);
result[indexOf] = take.get();
System.out.println("result=" + result[indexOf]);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* /.
*
*/
public static TaskStack flowTask(FlowTask task) {
return new TaskStack(task);
}
/**
* /
*/
public static class TaskStack {
private final Queue<FlowTask> taskFlowQueue = new ConcurrentLinkedQueue();
private final TaskEvent event = new TaskEvent() {
@Override
public void next(Object[] arg) {
FlowTask next = taskFlowQueue.poll();
if (next == null) {
return;
}
next.onTask(event, arg);
}
};
public TaskStack(FlowTask first) {
this.taskFlowQueue.add(first);
}
public void start(Object... arg) {
FlowTask first = this.taskFlowQueue.poll();
if (first == null) {
return;
}
first.onTask(event, arg);
}
public TaskStack then(FlowTask task) {
this.taskFlowQueue.add(task);
return this;
}
}
/**
* /
*/
public interface TaskEvent {
/**
*
*
* @param arg
*/
void next(Object... arg);
}
/**
*
*/
public interface FlowTask {
/**
*
*
* @param flow
* @param arg
*/
void onTask(TaskEvent flow, Object... arg);
}
}
Loading…
Cancel
Save

Powered by TurnKey Linux.