在特定时间运行java线程 [英] Run java thread at specific times

查看:120
本文介绍了在特定时间运行java线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,每小时与中央数据库同步4次。该过程通常需要2分钟。我想以X:55,X:10,X:25和X:40的线程运行这个过程,以便用户知道在X:00,X:15,X:30和X:45他们有一个干净的数据库副本。这只是管理期望。我已经经历了 java.util.concurrent 中的执行器,但是调度使用我相信提供的 scheduleAtFixedRate 没有保证,当这是实际运行的时间。我可以使用第一次延迟启动 Runnable ,以使第一个接近发射时间和计划为每15分钟,但似乎这可能会在时间上分歧。

I have a web application that synchronizes with a central database four times per hour. The process usually takes 2 minutes. I would like to run this process as a thread at X:55, X:10, X:25, and X:40 so that the users knows that at X:00, X:15, X:30, and X:45 they have a clean copy of the database. It is just about managing expectations. I have gone through the executor in java.util.concurrent but the scheduling is done with the scheduleAtFixedRate which I believe provides no guarantee about when this is actually run in terms of the hours. I could use a first delay to launch the Runnable so that the first one is close to the launch time and schedule for every 15 minutes but it seems that this would probably diverge in time. Is there an easier way to schedule the thread to run 5 minutes before every quarter hour?

推荐答案

你可以让Runnable安排它的时间表next run。

You can let the Runnable schedule its "next run".

如:

class Task implements Runnable {
    private final ScheduledExecutorService service;

    public Task(ScheduledExecutorService service){
        this.service = service;
    }

    public void run(){
        try{
             //do stuff
        }finally{
            //Prevent this task from stalling due to RuntimeExceptions.
            long untilNextInvocation = //calculate how many ms to next launch
            service.schedule(new Task(service),untilNextInvocation,TimeUnit.MILLISECONDS);
        }
    }
}

这篇关于在特定时间运行java线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆