标签:ini news 异常 main center col ble 微服务 lte
这种实现方式是阿里规范不推荐的使用方式,有资源耗尽的风险
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* @author Created by niugang on 2019/10/17/14:40
*/
public class ScheduledExecutorTest {
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final Runnable beeper = new Runnable() {
@Override
public void run() {
System.out.println("beep");
}
};
/**
* initialDelay:首次执行延迟的时间
* period:连续执行之间的一段时间
*/
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
@Override
public void run() {
System.out.println("任务取消了");
beeperHandle.cancel(true);
}
}, 60, SECONDS);
}
}
推荐的方式
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author Created by niugang on 2019/10/17/15:10
*/
public class ScheduledThreadPoolTest {
private static ScheduledThreadPoolExecutor executor;
static {
executor = new ScheduledThreadPoolExecutor(5, new ThreadFactoryBuilder()
.setNameFormat("Scheduled-thread").build());
}
public static void main(String[] args) {
ScheduledFuture<?> scheduledFuture = executor.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
System.out.println("Execute work task:" + new Date());
}
} , 10, 10, TimeUnit.SECONDS);
System.out.println(scheduledFuture.isCancelled());
//scheduledFuture.isDone() 如果此任务已完成,则返回true。完成可能是由于正常的终止、异常或取消——在所有这些情况下,此方法都将返回true。
//scheduledFuture.isCancelled()) 如果此任务在正常完成之前被取消,则返回true
executor.schedule(new Runnable() {
@Override
public void run() {
System.out.println("取消任务");
//尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表。
scheduledFuture.cancel(true);
System.out.println(scheduledFuture.isCancelled());
}
}, 60, TimeUnit.SECONDS);
}
}
@SpringBootApplication
@Slf4j
public class DemoApplication implements ApplicationRunner {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(ApplicationArguments args) {
threadPoolTaskScheduler.scheduleAtFixedRate(() -> log.info("SPRING BOOT SCHEDULE"), new Date(),5000);
}
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
}
先使用jdk自带的,如果满足不了在使用spring提供的,如果在还满足不了可以借助三方插件
微信公众号
标签:ini news 异常 main center col ble 微服务 lte
原文地址:https://www.cnblogs.com/niugang0920/p/12187014.html