如何在java中定期执行操作? [英] How to do an action in periodic intervals in java?

查看:148
本文介绍了如何在java中定期执行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法创建一个循环,可以每3秒执行一次任务而不使用睡眠功能

Is there any way of creating a loop that would do the task every 3 secs without using a sleep function

例如:

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

但使用睡眠功能时的问题是,它只会冻结程序。

But the problem while using sleep function is that, it just freezes the program.


这个循环的主要思想是与mysql数据库
(在线)同步。

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。计时器,例如:

If you are using a GUI, you can use the javax.swing.Timer, example:

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.Timer java.swing.Timer
http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html


它和javax.swing.Timer都提供相同的基本功能,
但java.util.Timer更通用,并且具有更多功能。
javax.swing.Timer有两个功能,可以让你使用GUI更容易
。首先,它的事件处理隐喻对于GUI
程序员来说是熟悉的,并且可以使事件调度线程更简单地处理
。其次,它的自动线程共享意味着你没有
必须采取特殊步骤来避免产生太多线程。
相反,你的计时器使用相同的线程来使光标闪烁,出现
工具提示,依此类推。

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中定期执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆