Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Timer?

Tags:

java

timer

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())

like image 635
Soheil Avatar asked Jul 10 '26 08:07

Soheil


2 Answers

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

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

            }
        }, 400);
like image 88
fmodos Avatar answered Jul 13 '26 20:07

fmodos


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

like image 39
Daniela Mogini Avatar answered Jul 13 '26 19:07

Daniela Mogini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!