java - 如何在 java 中以周期性间隔执行操作?

标签 java loops timer

有没有办法创建一个循环,每 3 秒执行一次任务,而无需使用 sleep 功能

例如:

try {
    while (true) {
        System.out.println(new Date());
        Thread.sleep(5 * 1000);
    }
} catch (InterruptedException e) {
    e.printStackTrace();
}

但是使用 sleep 函数的问题是,它只是卡住了程序。

The main idea of this loop is to get a sync with mysql database (online).

最佳答案

使用java.util.TimerTask

java.util.Timer t = new java.util.Timer();
t.schedule(new TimerTask() {

            @Override
            public void run() {
                System.out.println("This will run every 5 seconds");

            }
        }, 5000, 5000);

如果您使用的是 GUI,则可以使用 javax.swing.Timer,示例:

int delay = 5000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          System.out.println("This will run every 5 seconds");
      }
  };
  new javax.swing.Timer(delay, taskPerformer).start();

关于 java.util.Timerjava.swing.Timer 之间区别的一些信息: http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

Both it and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. The javax.swing.Timer has two features that can make it a little easier to use with GUIs. First, its event handling metaphor is familiar to GUI programmers and can make dealing with the event-dispatching thread a bit simpler. Second, its automatic thread sharing means that you don't have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread used to make cursors blink, tool tips appear, and so on.

关于java - 如何在 java 中以周期性间隔执行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17397259/

相关文章:

java - 使用 sharedpreferences 保存一个数组列表并在 ListView 中显示

swift - 我正在尝试创建一个函数,如果他们在晋升名单上,就会增加员工的工资

java - 停止 Java 计时器

java - 在服务器上上传文件时出错

java - 如何使用别名获取KMS KeyId?

php - 在 if 条件中放置一个 foreach 循环

Java字符串循环在数字后停止

javascript - 倒计时器 - 凌乱的 Javascript 函数

ios - NSTimer/定时器持续时间和 UI 更新

java - 为什么我会出现空指针异常?