• 定时任务 ScheduledExecutorService


    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.*;
    
    /**
     * ScheduledExecutorService是从Java SE 5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。
     * 相比于上两个方法(普通thread和用Timer、TimerTask),它有以下好处:
     * 相比于Timer的单线程,它是通过线程池的方式来并发执行任务的
     * 可以很灵活的去设定第一次执行任务delay时间
     * 提供了良好的约定,以便设定执行的时间间隔
     */
    public class Timer implements Runnable  {
    
        private String something;
        private int index = 0;
    
        public Timer(String something) {
            this.something = something;
        }
    
        @Override
        public void run() {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if("beautiful".equals(something)) {
                if (index == "beautiful".length()) {
                    System.out.println();
                    System.out.println(df.format(new Date()) + "  " + "beautiful!!!");
                    index = 0;
                } else {
                    if (index == 0)
                        System.out.print(df.format(new Date()) + "  ");
                    System.out.print("beautiful".charAt(index));
                    index++;
                }
            }else{
                System.out.println(df.format(new Date())+"  "+something);
            }
        }
    
        public static void main(String[] args) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
            ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
            System.out.println(df.format(new Date())+"  you are");
    
            long initialDelay1 = 1;
            //从现在开始1秒钟之后,只执行一次
            service.schedule(new Timer("... ..."), initialDelay1,TimeUnit.SECONDS);
    
            long initialDelay2 = 2; //延迟
            long period2 = 1; //间隔
            // 从现在开始2秒钟之后,每隔1秒钟执行一次
            // scheduleAtFixedRate 每隔固定的时间,立即执行下一次。(scheduleWithFixedDelay 等上一次任务执行完毕,才会执行下一次)
            service.scheduleAtFixedRate(new Timer("beautiful"),initialDelay2, period2, TimeUnit.SECONDS);
        }
    }

    结果:

    2018-09-19 14:01:52  you are
    2018-09-19 14:01:53  ... ...
    2018-09-19 14:01:54  beautiful
    2018-09-19 14:02:03  beautiful!!!
    2018-09-19 14:02:04  beautiful
    2018-09-19 14:02:13  beautiful!!!
    。。。
  • 相关阅读:
    RabbitMQ安装(发生系统错误5。拒绝访问。发生系统错误1067。进程意外终止。)
    SQLServer执行脚本提示“系统找不到指定的文件”或“内存资源不足”
    TypeScript@HelloWorld!
    超详细Node安装教程
    进制转换
    菜鸟成长记
    ASP.NET Core中使用MialKit实现邮件发送
    VS未能正确加载 ”Microsoft.VisualStudio.Editor.Implementation.EditorPackate“包错误解决方法
    C#Winfrom Listview数据导入Excel
    安装研发服务器
  • 原文地址:https://www.cnblogs.com/shushengyou/p/9674245.html
Copyright © 2020-2023  润新知