安排一个“命名”任务,以便我可以重新安排它

时间:2013-12-06 03:20:28

标签: java timer scheduled-tasks

我使用TimerTimerTasks来安排执行某些任务。某些任务必须重新安排。我需要一种机制来“命名”任务(例如通过字符串ID),这样我就可以重新安排它们或删除它们并在新的时间安排它们。

我正在研究的项目是飞行显示系统。插入数据库时​​的每个航班都有预定的到达和离开时间。因此,当必须显示航班时,我会使用一个计时器任务来更新机场显示,而另一个则用于隐藏它。

在飞行时间发生变化之前,一切都很好。用户更新数据库中的时间,但我需要重新安排显示更新时间。这是我需要你帮助的地方。

2 个答案:

答案 0 :(得分:3)

您如何看待简单的HashMap<UUID, TimerTask> tasks。您可以通过给定ID找到任何任务,取消它,或稍后重新安排。

<强>更新

public class TimerThingy{
    HashMap<UUID,TimerTask> tasks = new HashMap<UUID,TimerTask>();
    Timer timer = new Timer();

    public UUID createAndStartTimer(final Runnable task, Date when){
        TimerTask timerTask = new TimerTask(){
            public void run(){
                task.run();
            }
        }
        timer.schedule(TimerTask timerTask, Date when);
        UUID id = UUID.randomUUID(); 
        tasks.put(id, t);
        return id;
    }

    public void cancelTimer(UUID id){
        tasks.get(id).cancel();
    }

}

这是一种最简单的调度程序,可以取消ID。我想你可能会使用其他东西作为ID,因为你可能会找到正确的取消任务。但那取决于你......

答案 1 :(得分:1)

//您可以创建一个存储任务的地图,并按ID编制索引。

Map<String,TimerTask> tasks = new HashMap<String,TimerTask>();

您使用函数生成命名任务:

public TimerTask createTask(String name, final Runnable r){
    TimerTask task = new TimerTask(){
        public void run(){
            r.run();
        }
    }

    //here, you save it to the HashMap 
    tasks.put(name, task);
    return task;
}

//必须显示航班时才会显示更新机场,而另一个航班则会隐藏它。

现在,要创建一个任务,您可以像以前一样创建runnable,并创建您希望它拥有的名称,例如fligthnumer-show或flightnumer-hide,然后调用该函数来创建任务。

Runnable r= ...  //whatever you does here
String name = "1234-show";
TimerTask task = createTask( name,   r);

现在,您可以安排任务,或做任何您需要的事情。此外,您的任务已保存,因此,如果您再次需要它,取消它或再次安排它,您只需要从hashmap中检索它,调用它的名称:

 TimerTask task = tasks.get("1234-show");

在这个例子中,它并不是真正有用,但在您的实际应用程序中,例如,如果您正在创建任务,则很容易构建动态的任务列表。假设您必须安排一项任务来显示信息或新航班,这可能是您前一天已经完成的,或者可能是新航班。您可以检查是否已经有任务,如果有,您可以使用它,否则您将其创建并保存。

//say you have flight number in a var called flightNumber, and you are building a "show" task 
String name= flightNumber+"show";

TimerTask task = tasks.get(name); //if the task is found, you can use it

//instead, f there is not such task, null will be returned,  in that case, you create it.
if (null== task) {
    //do al the required stuff, like get the runnable ready, and create the task
    task = createTask( name,   r);
}

//so here, you can do whatever you need with the task
相关问题