How to start a thread after specified time delay in java

前端 未结 5 882
轮回少年
轮回少年 2020-12-14 07:59

I have called a method in ServletContextListener as thread ..Now as per my need i have to delay the thread for 1 minutes and then start executing the method called in the th

5条回答
  •  清歌不尽
    2020-12-14 08:16

    Or you can delay creating the thread with Timer and TimerTask:

    public void contextInitialized() {
        // Do your startup work here
        System.out.println("Started....");
    
        Timer timer = new Timer();
    
        TimerTask delayedThreadStartTask = new TimerTask() {
            @Override
            public void run() {
    
                //captureCDRProcess();
                //moved to TimerTask
                new Thread(new Runnable() {
                    @Override
                    public void run() {
    
                        captureCDRProcess();
                    }
                }).start();
            }
        };
    
        timer.schedule(delayedThreadStartTask, 60 * 1000); //1 minute
    }
    

提交回复
热议问题