How to make a Timer?

2019-04-10 18:04发布

I want to make a Timer that waits 400 MSc and then goes and prints "hi !" (e.g.). I know how to do that via javax.swing.Timer

    ActionListener action = new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
       System.out.println("hi!");
    }
};

plus :

    timer = new Timer(0, action);
    timer.setRepeats(false);
    timer.setInitialDelay(400);
    timer.start();

but as I know this definitely is not a good way as this kind of Timer is for Swing works. how to do that in it's correct way? (without using Thread.sleep())

标签: java timer
4条回答
欢心
2楼-- · 2019-04-10 18:22
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class currentTime {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        System.out.println( sdf.format(cal.getTime()) );
    }

}
查看更多
等我变得足够好
3楼-- · 2019-04-10 18:28

TimeUnit.MILLISECONDS.sleep(150L);

is an alternative;

You could also take a look at this Question

Which suggests using a while loop which just waits or a ScheduledThreadPoolExecutor

查看更多
混吃等死
4楼-- · 2019-04-10 18:32

You can consider Quartz scheduler, it's a really scalable, easy to learn and to configure solution. You can have a look at the tutorials on the official site.
http://quartz-scheduler.org/documentation/quartz-2.1.x/quick-start

查看更多
何必那么认真
5楼-- · 2019-04-10 18:41
Timer t = new Timer();
t.schedule(new TimerTask() {

            @Override
            public void run() {
                System.out.println("Hi!");

            }
        }, 400);
查看更多
登录 后发表回答