Soheil
Soheil

Reputation: 1706

How to make a 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())

Upvotes: 3

Views: 25031

Answers (4)

Kafi
Kafi

Reputation: 11

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

}

Upvotes: 1

Daniela Mogini
Daniela Mogini

Reputation: 299

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

Upvotes: 1

fmodos
fmodos

Reputation: 4568

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

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

            }
        }, 400);

Upvotes: 10

Moritz Roessler
Moritz Roessler

Reputation: 8611

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

Upvotes: 0

Related Questions