Java的:几秒钟的具体数目后运行的功能

问题描述 投票:124回答:10

我有我要在5秒后要执行的特定功能。我如何能做到这一点在Java中?

我发现javax.swing.Timer中,但我无法真正了解如何使用它。它看起来像我在找东西的方式更简单那么这个类提供。

请添加一个简单的使用例子。

java timer
10个回答
205
投票
new java.util.Timer().schedule( 
        new java.util.TimerTask() {
            @Override
            public void run() {
                // your code here
            }
        }, 
        5000 
);

编辑:

javadoc说:

最后现场引用一个Timer对象消失,所有未完成的任务已完成执行后,计时器的任务执行线程终止优雅(并成为受垃圾收集)。然而,这可能需要任意长的发生。


2
投票
public static Timer t;

public synchronized void startPollingTimer() {
        if (t == null) {
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                   //Do your work
                }
            };

            t = new Timer();
            t.scheduleAtFixedRate(task, 0, 1000);
        }
    }

51
投票

事情是这样的:

// When your program starts up
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

// then, when you want to schedule a task
Runnable task = ....    
executor.schedule(task, 5, TimeUnit.SECONDS);

// and finally, when your program wants to exit
executor.shutdown();

上有Executor其他各种工厂方法这,如果你想在游泳池更多的线程,你可以改用。

请记住,重要的是要关闭的执行,当你完成。该shutdown()方法将完全关闭线程池当最后一个任务已经完成,将阻塞,直到发生这种情况。 shutdownNow()将立即终止线程池。


21
投票

使用javax.swing.Timer的实施例

Timer timer = new Timer(3000, new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent arg0) {
    // Code to be executed
  }
});
timer.setRepeats(false); // Only execute once
timer.start(); // Go go go!

该代码将只被执行一次,并且执行在3000毫秒(3秒)发生的情况。

作为camickr提到,你应该查找“How to Use Swing Timers”一个简短的介绍。


6
投票

我的代码如下:

new java.util.Timer().schedule(

    new java.util.TimerTask() {
        @Override
        public void run() {
            // your code here, and if you have to refresh UI put this code: 
           runOnUiThread(new   Runnable() {
                  public void run() {
                            //your code

                        }
                   });
        }
    }, 
    5000 
);

5
投票

作为@tangens的变化回答:如果你不能等待垃圾收集器来清理你的线程,取消计时器在你的run方法结束。

Timer t = new java.util.Timer();
t.schedule( 
        new java.util.TimerTask() {
            @Override
            public void run() {
                // your code here
                // close the thread
                t.cancel();
            }
        }, 
        5000 
);

4
投票

你原来的问题提到了“摇摆定时器”。事实上,如果你的问题是摆动的关系,那么你就应该使用Swing的计时器,而不是util.Timer。

阅读从Swing教程“How to Use Timers”一节以获取更多信息。


3
投票

你可以使用Thread.sleep代码()函数

Thread.sleep(4000);
myfunction();

你的功能4秒钟后就会执行。然而,这可能会暂停整个程序...


2
投票

ScheduledThreadPoolExecutor有这个能力,但它是相当重量级的。

Timer也有这个能力,但打开即使只使用一次的几个线程。

这里有一个简单的实现与测试(签名接近Android的Handler.postDelayed()):

public class JavaUtil {
    public static void postDelayed(final Runnable runnable, final long delayMillis) {
        final long requested = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        long leftToSleep = requested + delayMillis - System.currentTimeMillis();
                        if (leftToSleep > 0) {
                            Thread.sleep(leftToSleep);
                        }
                        break;
                    } catch (InterruptedException ignored) {
                    }
                }
                runnable.run();
            }
        }).start();
    }
}

测试:

@Test
public void testRunsOnlyOnce() throws InterruptedException {
    long delay = 100;
    int num = 0;
    final AtomicInteger numAtomic = new AtomicInteger(num);
    JavaUtil.postDelayed(new Runnable() {
        @Override
        public void run() {
            numAtomic.incrementAndGet();
        }
    }, delay);
    Assert.assertEquals(num, numAtomic.get());
    Thread.sleep(delay + 10);
    Assert.assertEquals(num + 1, numAtomic.get());
    Thread.sleep(delay * 2);
    Assert.assertEquals(num + 1, numAtomic.get());
}

2
投票

所有其他unswers需要运行一个新线程的代码。在一些简单的使用情况下,你可能只是想等待一下,在同一个线程/流中继续执行。

下面的代码演示了该技术。请记住,这是类似于java.util.Timer的引擎盖,但更轻巧的下呢。

import java.util.concurrent.TimeUnit;
public class DelaySample {
    public static void main(String[] args) {
       DelayUtil d = new DelayUtil();
       System.out.println("started:"+ new Date());
       d.delay(500);
       System.out.println("half second after:"+ new Date());
       d.delay(1, TimeUnit.MINUTES); 
       System.out.println("1 minute after:"+ new Date());
    }
}

delayutsya实施

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class DelayUtil {
    /** 
    *  Delays the current thread execution. 
    *  The thread loses ownership of any monitors. 
    *  Quits immediately if the thread is interrupted
    *  
    * @param duration the time duration in milliseconds
    */
   public void delay(final long durationInMillis) {
      delay(durationInMillis, TimeUnit.MILLISECONDS);
   }

   /** 
    * @param duration the time duration in the given {@code sourceUnit}
    * @param unit
    */
    public void delay(final long duration, final TimeUnit unit) {
        long currentTime = System.currentTimeMillis();
        long deadline = currentTime+unit.toMillis(duration);
        ReentrantLock lock = new ReentrantLock();
        Condition waitCondition = lock.newCondition();

        while ((deadline-currentTime)>0) {
            try {
                lock.lockInterruptibly();    
                waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            } finally {
                lock.unlock();
            }
            currentTime = System.currentTimeMillis();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.