如何在java中指定的时间延迟后启动线程

我在ServletContextListener中调用了一个方法作为线程.现在,根据我的需要,我必须将线程延迟1分钟,然后开始执行线程中调用的方法,但我无法做到这一点,因为我在这方面非常新...

这是我的代码...

public class Startup implements ServletContextListener {

@Override
public void contextDestroyed(ServletContextEvent sce) {
}

public void contextInitialized(ServletContextEvent sce) {
    // Do your startup work here
    System.out.println("Started....");
    //captureCDRProcess();
    new Thread(new Runnable() {

        @Override
        public void run() {

            captureCDRProcess();
        }
    }).start();

}

请帮帮我..提前致谢..


答案 1

要正确执行此操作,您需要使用 ScheduledThreadPoolExecutor 并使用函数 schedule,如下所示:

final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);
executor.schedule(new Runnable() {
  @Override
  public void run() {
    captureCDRProcess();
  }
}, 1, TimeUnit.MINUTES);

Thread.sleep不是要走的路,因为它不能保证它在一分钟后醒来。根据操作系统和后台任务的不同,它可能是 60 秒、62 秒或 3 小时,而上面的计划程序实际上使用正确的操作系统实现进行计划,因此更加准确。

此外,此计划程序还允许其他几种灵活的方式来计划任务,例如以固定速率或固定延迟。

编辑:使用新的 Java8 Lamda 语法的相同解决方案:

final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);
executor.schedule(() -> captureCDRProcess(), 1, TimeUnit.MINUTES);

答案 2

或者,您可以延迟使用 Timer 和 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
}