我有代码,我在那里安排任务使用java.util.Timer.我环顾四周,看到ExecutorService可以做同样的事情.所以这个问题,你有没有使用Timer和Timer计划任务,一个人使用另一个人的好处是什么?
还想检查是否有人使用过该ExecutorService课程并遇到了Timer为他们解决的任何问题.
我知道Deamon线程背景线程.我们可以通过调用创建自己的守护进程线程setDaemon(true).
我的问题是:为什么以及何时需要创建我们的线程作为守护程序线程?
我想每天下午2点执行一份工作.java.util.Timer我可以用哪种方法安排工作?
2小时后,它将停止工作并重新安排在第二天下午2点.
我想延迟做一些事情,就像设置倒计时器一样,在一段时间后"做一件事".
我希望我的其余程序在我等待的时候继续运行,所以我尝试自己Thread创建一个包含一分钟延迟的程序:
public class Scratch {
private static boolean outOfTime = false;
public static void main(String[] args) {
Thread countdown = new Thread() {
@Override
public void run() {
try {
// wait a while
System.out.println("Starting one-minute countdown now...");
Thread.sleep(60 * 1000);
// do the thing
outOfTime = true;
System.out.println("Out of time!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
countdown.start();
while (!outOfTime) {
try {
Thread.sleep(1000);
System.out.println("do other stuff here");
} catch (InterruptedException e) {
e.printStackTrace(); …Run Code Online (Sandbox Code Playgroud) 我有一个代码必须在未来的某个日期时间执行,假设我有一个未来的日期,并且我想在未来的该日期 +1 分钟内执行一段代码,但仅限一次。我知道我要使用 java Timer 和 TimerTask 来执行此操作。例如,执行以下操作:
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Calendar myDate = Calendar.getInstance();
myDate.add(Calendar.MINUTE, 1);
Date afterOneMinute = myDate.getTime();
System.out.println("Scheduled at:" + afterOneMinute);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Executed at:" + (new Date()));
}
}, afterOneMinute);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种使用ScheduledExecutorService进行相同操作的优雅方法,以便拥有一个特定的池,因为该池将用于多个调用。有人可以帮助我吗?