如何在运行时更改TimerTask的执行周期?

时间:2011-06-29 11:42:49

标签: java timer timertask

如何在运行时更改定时器的周期?

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {

             // read new period
             period = getPeriod();

             doSomething();

        }
    }, 0, period);

3 个答案:

答案 0 :(得分:6)

您不能直接执行此操作,但可以取消Timer上的任务,并使用所需的时间段重新安排这些任务。

没有getPeriod方法。

答案 1 :(得分:3)

你可以这样做:

private int period= 1000; // ms

private void startTimer() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
            // do something...
            System.out.println("period = " + period);
            period = 500;   // change the period time
            timer.cancel(); // cancel time
            startTimer();   // start the time again with a new period time
        }
    }, 0, period);
}

答案 2 :(得分:0)

您可以使用以下类在运行时更改self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2; self.imageView.clipsToBounds = YES; self.imageView.layer.borderWidth = 3.0f; self.imageView.layer.borderColor = [UIColor whiteColor].CGColor; 的执行周期。

正如已经说明的,它不能真正更改时间段,而必须取消并重新安排任务:

TimerTask

计时器可以这样启动:

import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.function.Supplier;

/**
 * {@link TimerTask} with modifiable execution period.
 * 
 * @author Datz
 */
public class EditablePeriodTimerTask extends TimerTask {

    private Runnable task;
    private Supplier<Long> period;
    private Long oldP;

    /**
     * Constructor with task and supplier for period
     * 
     * @param task the task to execute in {@link TimerTask#run()}
     * @param period a provider for the period between task executions
     */
    public EditablePeriodTimerTask(Runnable task, Supplier<Long> period) {
        super();
        Objects.requireNonNull(task);
        Objects.requireNonNull(period);
        this.task = task;
        this.period = period;
    }

    private EditablePeriodTimerTask(Runnable task, Supplier<Long> period, Long oldP) {
        this(task, period);
        this.oldP = oldP;
    }

    public final void updateTimer() {
        Long p = period.get();
        Objects.requireNonNull(p);
        if (oldP == null || !oldP.equals(p)) {
            System.out.println(String.format("Period set to: %d s", p / 1000));
            cancel();
            new Timer().schedule(new EditablePeriodTimerTask(task, period, p), p, p);
            // new Timer().scheduleAtFixedRate(new EditablePeriodTimerTask(task, period), p, p);
        }
    }

    @Override
    public void run() {
        task.run();
        updateTimer();
    }

}

EditablePeriodTimerTask editableTimerTask = new EditablePeriodTimerTask(runnable, () -> getPeriod()); editableTimerTask.updateTimer(); 是要执行的真实任务,runnable提供了两次任务执行之间的时间间隔。当然,哪个可以根据您的要求进行更改。