How to make a timer?

I want to do Timer

that waits for 400 MSc and then goes and prints “hello!”. (eg.). I know how to do it throughjavax.swing.Timer

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

      

a plus:

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

      

but as I know it is definitely not very good since this type Timer

works for Swing. how to do it right? (without use Thread.sleep()

)

+3


source to share


4 answers


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

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

            }
        }, 400);

      



+9


source


You may want to consider the Quartz Scheduler, which is a truly scalable, easily trainable and customizable solution. You can check the tutorials on the official website.
http://quartz-scheduler.org/documentation/quartz-2.1.x/quick-start



+1


source


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

}

      

+1


source


TimeUnit.MILLISECONDS.sleep(150L);

is an alternative;

You can also take a look at this Question

Which suggests using a loop while

that just waits or a ScheduledThreadPoolExecutor

0


source







All Articles