有什么好的方法,用类库来实现...
我想要一个java程序有一个时间列表[上午8.47,上午8.49,晚上9..],并且当到达每个时间时,运行一些代码(启动单独的JAR)。我可以尝试一下,但需要一些指导,例如用于计时器的最佳类。也许有些是阻塞/非阻塞的。
谢谢。
最佳答案
我们可以通过使用内部实现 runnable 接口(interface)的 TimerTask 类来做到这一点。 声明一个 arrayList 并在其中插入所需的时间,并且将相应地安排方法调用。
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
//The task which you want to execute
class MyTimeTask extends TimerTask
{
public void run()
{
System.out.println("DO some task");
}
public static void main(String[] args) throws ParseException {
//the Date and time at which you want to execute
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm a");
Date date = dateFormatter.parse("2018-05-23 12:43 am");
Date date1 = dateFormatter.parse("2018-05-23 12:43 pm");
ArrayList<Date> d=new ArrayList<>();
d.add(date);
d.add(date1);
//Now create the time and schedule it
Timer timer = new Timer();
//Use this if you want to execute it once
for(Date dd:d){
timer.schedule(new MyTimeTask(),dd);
}
//Use this if you want to execute it repeatedly
//int period = 10000;//10secs
//timer.schedule(new MyTimeTask(), date, period );
}
}
关于Java定时器代码执行JAR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50481264/