如何在java中运行多个计时器任务,例如在20秒内超时,但所有计时任务都在不同的时间启动,但是它们在创建后的20秒后仍然运行。我计划接收很多我需要保留一段时间的任务,然后在秒数消失后触发另一个事件。
可以同时运行多个任务。 我见过http://www.quartz-scheduler.org/overview/quick-start,但我想知道是否还有另一种方法可以实现我的目标。
答案 0 :(得分:1)
这是使用java.utils包执行此操作的一种方法:
ul
如果您之前使用过Java 8(或想要使用它),您可以尝试使用此代码:
public class Main {
private static final int delayMilliseconds = 20000; // 20 seconds
private static Timer timer;
public static void main(String[] args) throws Exception{
System.out.println("START");
// Create a Timer
timer = new Timer();
doTask();
Thread.sleep(1000);
doTask();
Thread.sleep(1000);
doTask();
Thread.sleep(1000);
doTask();
Thread.sleep(1000);
System.out.println("END");
}
public static final void doTask(){
System.out.println("Started at: " + Calendar.getInstance().getTime());
System.out.println("Perform your task here");
// Create new task
TimerTask task = new TimerTask() {
@Override
public void run() {
// Run the "timeout finished" function here.
System.out.println("Timed out! " + Calendar.getInstance().getTime());
}
};
// Schedule a task for in 20 seconds in the future.
timer.schedule(task, delayMilliseconds);
}
}
第二种方法使它可以将函数传递给
public class Main {
private static final int delayMilliseconds = 20000; // 20 seconds
private static Timer timer;
public static void main(String[] args) throws Exception{
System.out.println("START");
// Create a Timer
timer = new Timer();
doTask(() -> System.out.println("Task 1"));
Thread.sleep(1000);
doTask(() -> System.out.println("Task 2, starting a second later"));
Thread.sleep(1000);
doTask(() -> System.out.println("Task 3, starting a second later"));
Thread.sleep(1000);
doTask(() -> System.out.println("Task 4, starting a second later"));
Thread.sleep(1000);
System.out.println("END");
}
public static final void doTask(Runnable function) throws Exception{
System.out.println("Started at: " + Calendar.getInstance().getTime());
// Run the function here
function.run();
// Create new task
TimerTask task = new TimerTask() {
@Override
public void run() {
// Run the "timeout finished" function here.
System.out.println("Timed out! " + Calendar.getInstance().getTime());
}
};
// Schedule a task for in 20 seconds in the future.
timer.schedule(task, delayMilliseconds);
}
}
函数。查看 this link 以获取有关Timer类的更多信息,并查看 this link 以获取有关java 8中lambda的更多信息::)