newbee
newbee

Reputation: 409

Using Swing Timer to delay task

I am using Swing Timer to delay my task for a specific period of time. This time interval is decided by the user.

In my GUI, I have a SpinnerDateModel to accept the time at which the task has to be performed.

SpinnerDateModel date = new SpinnerDateModel();
        JSpinner spinner = new JSpinner(date);          
        frame.getContentPane().add(spinner);            
        Date futureDate = date.getDate();

Now, Timer has arguments Timer(int delay, ActionListener task)

ActionListener task = new ActionListener(){

                    @Override
                    public void actionPerformed(ActionEvent arg0) {

                        //send function
                    }

                };
                Timer timer = new Timer(delay, task);
                timer.setRepeats(false);                
                timer.start();

How do I set this delay to the time specified by the user?

Upvotes: 0

Views: 1480

Answers (1)

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64065

With some checking to prevent a negative delay, something like:

delay=Math.max(0,futureDate.getTime()-System.currentTimeMillis());
delay=Math.min(delay,Integer.MAX_VALUE);
// or:
//   if(delay>Integer.MAX_VALUE) { throw new exception-of-some-sort }
Timer timer=new Timer((int)delay,task);

should do the trick.

This will calculate the delay based on the number of milliseconds from now until the (presumed future) date selected by the user.

Upvotes: 1

Related Questions