Java Timer

后端 未结 3 749
萌比男神i
萌比男神i 2020-11-29 10:05

I\'m trying to use a timer to schedule a recurring event in an application. However, I want to be able to adjust the period at which the event fires in real time (according

相关标签:
3条回答
  • 2020-11-29 10:36

    It seems odd to me to have a TimerTask with its own Timer inside it. Bad design. I'd totally separate the two and have the TimerTask implementation be handed off to a Timer, and put all that logic about fiddling with the period inside another class that provides an interface for doing so. Let that class instantiate the Timer and TimerTask and send them off to do their work.

    0 讨论(0)
  • 2020-11-29 10:37

    You can't reuse a TimerTask as you're doing here.

    Relevant porition of Timer:

    private void sched(TimerTask task, long time, long period) {
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");
    
        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");
    
            synchronized(task.lock) {
                //Right here's your problem.
                //  state is package-private, declared in TimerTask
                if (task.state != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }
    
            queue.add(task);
            if (queue.getMin() == task)
                queue.notify();
        }
    }
    

    You'll need to refactor your code so that you create a new TimerTask, rather than re-using one.

    0 讨论(0)
  • 2020-11-29 10:57
        import java.util.*;
        class TimeSetting 
        {
        public static void main(String[] args)
        {
        Timer t = new Timer();
        TimerTask time = new TimerTask()
        { 
        public void run()
        {
        System.out.println("Executed......");
        }
        };
        t.scheduleAtFixedRate(time, 4000, 3000); 
        // The task will be started after 4 secs and 
        // for every 3 seconds the task will be continuously executed.....
        }
        }
    
    0 讨论(0)
提交回复
热议问题