3

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

Chris
  • 7,675
  • 8
  • 51
  • 101
Soheil
  • 1,676
  • 7
  • 34
  • 65

4 Answers4

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

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

            }
        }, 400);
fmodos
  • 4,472
  • 1
  • 16
  • 17
1

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

Daniela Mogini
  • 299
  • 1
  • 5
  • 17
  • why not using util.Timer ? – Soheil Jan 22 '13 at 08:25
  • 1
    It depends on what you have to do. If you need a complex condition involving the date, the time of the day and so on, it's better to use Quartz because it has a scheduler with great flexibility. You can establish conditions like every Wednesday of the month or every last day of the month at 12.00. It also give the possibility to repeat automatically a job more than once for example one per hour for 5 hours. On the other hand, for a simple timer, I'd use util.Timer too. – Daniela Mogini Jan 22 '13 at 08:40
1
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()) );
    }

}
josliber
  • 43,891
  • 12
  • 98
  • 133
Kafi
  • 11
  • 2
0

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

Community
  • 1
  • 1
Moritz Roessler
  • 8,542
  • 26
  • 51