欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ScheduledExecutorService用法

程序员文章站 2022-05-14 21:56:06
...

ScheduledExecutorService用法

初始化

简单用法

	
public class TestTask {

    /**
     * 定时任务执行器
     */
    private ScheduledExecutorService executorService;

    /**
     * 定时任务间隔时间
     */
    private long taskTime;

    public TestTask(int threadSize, long taskTime) {
        this.beatTaskTime = beatTaskTime;
        executorService = new ScheduledThreadPoolExecutor(threadSize, (r) -> {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            thread.setName("com.wmang.service.test");
            return thread;
        });
    }

    public void initBeatTask() { 
        executorService.scheduleAtFixedRate(() -> {
              // 定时任务执行逻辑
        }, beatTaskTime,beatTaskTime, TimeUnit.MILLISECONDS);
    }
}

方法解释

schedule(Runnable command, long delay, TimeUnit un