标签:slf4j static inf count 文件 service read int org
开发中偶尔会碰到一些轮询需求,比如我碰到的和银行对接,在做完某一个业务后银行没有同步给到结果,这时候就需要查询返回结果,我们的需求是5分钟一次,查询3次,3次过后如果没有结果则T+1等银行的文件,对于这种任务我们的要求是轮询不是很严格,所以我采取调度线程池方式,如果有查询任务,加入线程池,设置好执行次数及执行时间间隔,具体代码如下:
1 import org.junit.Test; 2 import org.slf4j.Logger; 3 import org.slf4j.LoggerFactory; 4 5 import java.util.concurrent.*; 6 7 8 public class LocalTest { 9 10 private static final Logger log = LoggerFactory.getLogger(LocalTest.class); 11 12 @Test 13 public void test01() throws InterruptedException { 14 ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); 15 ConcurrentHashMap<String, Future> futureMap = new ConcurrentHashMap<>(); 16 17 JobTest jobTest1 = new JobTest("job1",futureMap); 18 Future future1 = executorService.scheduleAtFixedRate(jobTest1,1, 5, TimeUnit.SECONDS); 19 futureMap.put(jobTest1.getJobId(),future1); 20 21 JobTest jobTest2 = new JobTest("job2",futureMap); 22 Future future2 = executorService.scheduleAtFixedRate(jobTest2,1, 5, TimeUnit.SECONDS); 23 futureMap.put(jobTest2.getJobId(),future2); 24 25 Thread.sleep(1000L * 30); 26 27 JobTest jobTest3 = new JobTest("job3",futureMap); 28 Future future3 = executorService.scheduleAtFixedRate(jobTest3,1, 5, TimeUnit.SECONDS); 29 futureMap.put(jobTest1.getJobId(),future3); 30 31 JobTest jobTest4 = new JobTest("job4",futureMap); 32 Future future4 = executorService.scheduleAtFixedRate(jobTest4,1, 5, TimeUnit.SECONDS); 33 futureMap.put(jobTest4.getJobId(),future4); 34 35 Thread.sleep(1000L * 300); 36 executorService.shutdown(); 37 } 38 39 @Test 40 public void test02() { 41 42 } 43 44 class JobTest implements Runnable { 45 46 private ConcurrentHashMap<String, Future> futureMap; 47 private int count = 0; 48 private String jobId; 49 50 public JobTest(){ 51 52 } 53 54 public JobTest(String jobId, ConcurrentHashMap<String, Future> futureMap) { 55 super(); 56 this.jobId = jobId; 57 this.futureMap = futureMap; 58 } 59 60 @Override 61 public void run() { 62 count++; 63 log.info("{} count is {}", jobId, count); 64 if (count > 2) { 65 Future future = futureMap.remove(jobId); 66 future.cancel(true); 67 log.info("{} had cancel", jobId); 68 } 69 } 70 71 public String getJobId() { 72 return jobId; 73 } 74 75 public void setJobId(String jobId) { 76 this.jobId = jobId; 77 } 78 79 public ConcurrentHashMap<String, Future> getFutureMap() { 80 return futureMap; 81 } 82 83 public void setFutureMap(ConcurrentHashMap<String, Future> futureMap) { 84 this.futureMap = futureMap; 85 } 86 } 87 }
由于任务是放在队列,在内存里面,所以应用重启会导致任务丢失,如果对于严格要求轮询查询的不合适用这种方式
ScheduledExecutorService调度线程池运行几次后停止某一个线程
标签:slf4j static inf count 文件 service read int org
原文地址:https://www.cnblogs.com/llf369/p/11485604.html