【问题标题】:Scheduling java process for a specific time interval with a given delay在给定延迟的特定时间间隔内调度 java 进程
【发布时间】:2015-08-24 03:07:39
【问题描述】:

我们希望安排一个 java 进程运行到一个特定的时间间隔。目前我正在考虑使用TimerTask 来安排这个过程。在每个循环开始时,将检查当前时间,然后与给定时间进行比较,如果时间已过则停止进程。 我们的代码如下所示:

import java.util.Timer;
import java.util.TimerTask;

public class Scheduler extends TimerTask{

    public void run(){
        //compare with a given time, with getCurrentTime , and do a System.exit(0);
        System.out.println("Output");
    }

    public static void main(String[] args) {
        Scheduler scheduler = new Scheduler();
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(scheduler, 0, 1000);

    }

}

有没有更好的方法?

【问题讨论】:

    标签: java scheduled-tasks scheduler schedule


    【解决方案1】:

    您可以为所述时间限制安排另一个任务并在计时器上调用取消,而不是检查每次迭代是否已达到时间限制。

    根据复杂性,您可能会考虑使用 ScheduledExecutorService,例如 ScheduledThreadPoolExecutor。 See in this answer when and why.

    带有计时器的简单工作示例:

    public class App {
        public static void main(String[] args) {
            final Timer timer = new Timer();
            Timer stopTaskTimer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    System.out.println("Output");
                }
            };
            TimerTask stopTask = new TimerTask() {
                @Override
                public void run() {
                    timer.cancel();
                }
            };
    
            //schedule your repetitive task
            timer.scheduleAtFixedRate(task, 0, 1000);
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = sdf.parse("2015-06-09 14:06:30");
                //schedule when to stop it
                stopTaskTimer.schedule(stopTask, date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

    • 感谢您的方法。我可以试试这个。
    • 感谢代码示例。我们可能会使用 ScheduledExecutorService ,但现在,上面的代码对我们来说是完美的。
    【解决方案2】:

    您可以使用RxJava,这是一个非常强大的响应式编程库。

    Observable t =  Observable.timer(0, 1000, TimeUnit.MILLISECONDS);
    t.subscribe(new Action1() {
                            @Override
                            public void call(Object o) {
                                System.out.println("Hi "+o);
                            }
                        }
    
    ) ;
    try {
        Thread.sleep(10000);
    }catch(Exception e){ }
    

    您甚至可以使用 lambda 语法:

    Observable t =  Observable.timer(0, 1000, TimeUnit.MILLISECONDS);
    t.forEach(it -> System.out.println("Hi " + it));
    try {
        Thread.sleep(10000);
    }catch(Exception e){  }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-15
      • 2012-06-23
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      相关资源
      最近更新 更多