本文介绍了如何安排任务运行一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想延迟做一些事情,就像设置倒数计时器一样,在一段时间后做一件事。 我想要我等待的其余程序继续运行,所以我尝试制作我自己的 Thread ,其中包含一分钟的延迟: public class Scratch { private static boolean outOfTime = false; public static void main(String [] args){ Thread countdown = new Thread(){ @Override public void run(){尝试{ //等待一段时间 System.out.println(现在开始一分钟倒计时...); Thread.sleep(60 * 1000); //做事物 outOfTime = true; System.out.println(超时!); } catch(InterruptedException e){ e.printStackTrace(); } } }; countdown.start(); while(!outOfTime){ try { Thread.sleep(1000); System.out.println(在这里做其他事情); } catch(InterruptedException e){ e.printStackTrace(); } } } } 虽然这或多或少有效,但似乎应该有更好的方法。 经过一番搜索,我找到了一堆像这样的问题,但它们并没有真正解决我想要做的事情: 如何安排任务定期运行? 我如何运行我的TimerTask每天下午2点 如何使用ScheduledExecutorService在特定时间每天运行某些任务? Java执行任务,具有多次重试和超时 我不需要任何复杂的东西;我只想在一段时间后做一件事,同时让程序的其余部分仍然运行。 我应该如何安排一次性任务做一件事?解决方案而 java.util.Timer 曾经是一个很好的方法安排未来的任务,现在优先使用 1 来使用 java.util.concurrent 包中的类。 有一个 ScheduledExecutorService 专门用于在延迟后运行命令(或定期执行命令,但这与此问题无关)。 它有一个 schedule(Runnable,long,TimeUnit) 方法 创建并执行在给定延迟后启用的一次性操作。 使用 ScheduledExecutorService 你可以像这样重写你的程序: import java.util.concurrent。*; public class Scratch { private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public static void main(String [] args){ System.out.println(现在开始倒计时一分钟......); ScheduledFuture<?> countdown = scheduler.schedule(new Runnable(){ @Override public void run(){ //做事物 System.out.println(超时 !); }},1,TimeUnit.MINUTES); while(!countdown.isDone()){ try { Thread.sleep(1000); System.out.println(在这里做其他事情); } catch(InterruptedException e){ e.printStackTrace(); } } scheduler.shutdown(); } } 通过这样做你得到的一件好事方式是您从调用 schedule()返回的 ScheduledFuture<?> 对象。 这允许您摆脱额外的布尔变量,并直接检查作业是否已运行。 如果您不想再通过调用 cancel() 方法。 1 参见 Java Timer vs ExecutorService?,原因是为了避免使用 Timer 支持 ExecutorService 。 / p> I want to delay doing something, along the lines of setting a countdown timer that will "do a thing" after a certain amount of time.I want the rest of my program to keep running while I wait, so I tried making my own Thread that contained a one-minute delay: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(); } } }}While this worked, more-or-less, it seemed like there should be a better way of doing this.After some searching, I found a bunch of questions like these but they don't really address what I'm trying to do:How do I schedule a task to run at periodic intervals?How i can run my TimerTask everyday 2 PMHow to run certain task every day at a particular time using ScheduledExecutorService?Java execute task with a number of retries and a timeoutI don't need anything this complicated; I just want to do a single thing after a certain amount of time while letting the rest of the program still run.How should I go about scheduling a one-time task to "do a thing"? 解决方案 While the java.util.Timer used to be a good way to schedule future tasks, it is now preferable1 to instead use the classes in the java.util.concurrent package.There is a ScheduledExecutorService that is designed specifically to run a command after a delay (or to execute them periodically, but that's not relevant to this question).It has a schedule(Runnable, long, TimeUnit) method that Creates and executes a one-shot action that becomes enabled after the given delay.Using a ScheduledExecutorService you could re-write your program like this:import java.util.concurrent.*;public class Scratch { private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public static void main(String[] args) { System.out.println("Starting one-minute countdown now..."); ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() { @Override public void run() { // do the thing System.out.println("Out of time!"); }}, 1, TimeUnit.MINUTES); while (!countdown.isDone()) { try { Thread.sleep(1000); System.out.println("do other stuff here"); } catch (InterruptedException e) { e.printStackTrace(); } } scheduler.shutdown(); }}One of the nice things you get by doing things this way is the ScheduledFuture<?> object you get back from calling schedule().This allows you to get rid of the extra boolean variable, and just check directly whether the job has run.You can also cancel the scheduled task if you don't want to wait anymore by calling its cancel() method.1See Java Timer vs ExecutorService? for reasons to avoid using a Timer in favor of an ExecutorService. 这篇关于如何安排任务运行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-03 19:06