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

3 ScheduledExecutorService

程序员文章站 2022-05-14 21:56:30
...
package cn.ys.timer;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestScheduledExecutorService {

    public static void main(String[] args) {

        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        /**
         * 参数:
         * 1、任务体
         * 2、首次执行的延时时间
         * 3、任务执行间隔
         * 4、间隔时间单位
         */
        service.scheduleAtFixedRate(
                ()->System.out.println("task ScheduledExecutorService: " + new Date()),
                0,
                3,
                TimeUnit.SECONDS);
    }
}

控制台每3秒打印一次时间:

task ScheduledExecutorService: Sat Aug 10 12:37:52 CST 2019
task ScheduledExecutorService: Sat Aug 10 12:37:55 CST 2019
task ScheduledExecutorService: Sat Aug 10 12:37:58 CST 2019
task ScheduledExecutorService: Sat Aug 10 12:38:01 CST 2019
......