我想在Java中编写一个循环,它首先启动并按以下方式运行:
while (!x){
//wait one minute or two
//execute code
}
我希望做到这一点,而不会使用系统资源。 实际上,代码正在访问一个网站并检查某些内容是否完成,如果没有完成,则应等待另一分钟再次检查,当完成后,它就会继续执行。 有没有办法在Java中实现这个功能?
你可以使用Timer
Timer timer = new Timer();
timer.schedule( new TimerTask() {
public void run() {
// do your work
}
}, 0, 60*1000);
当时机到来时
timer.cancel();
关闭它。
使用 Thread.sleep(long millis)
方法。
使当前线程暂停(暂时停止执行)指定的毫秒数,取决于系统计时器和调度程序的精度和准确性。线程不会失去任何监视器的所有权。
一分钟为 (60*1000) = 60000
毫秒。
例如,以下循环将每隔5秒钟打印一次当前时间:
try {
while (true) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
如果你的睡眠时间超过了 int
的范围,就要明确地使用 long
进行计算(例如 1000L
)。
Timer
类解决方案。 - Alan Thomasjava.util.concurrent
包是对此答案中所见代码的替代,也取代了Timer
类。请参阅ScheduledExecutorService
接口。 - Basil BourqueScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();
Executors.newSingleThreadScheduledExecutor()
代替Executors.newScheduledThreadPool(1);
。 - NicofisiScheduledExecutorService
Lee的回答很接近,但仅运行一次。问题似乎是要求在外部状态更改(直到来自网站/服务的响应更改)之前无限期运行。
ScheduledExecutorService
接口是Java 5及其后续版本中内置的java.util.concurrent
包的一部分,作为旧的Timer
类的现代替代品。
以下是完整示例。调用scheduleAtFixedRate
或scheduleWithFixedDelay
。
ScheduledExecutorService executor = Executors.newScheduledThreadPool ( 1 );
Runnable r = new Runnable () {
@Override
public void run () {
try { // Always wrap your Runnable with a try-catch as any uncaught Exception causes the ScheduledExecutorService to silently terminate.
System.out.println ( "Now: " + Instant.now () ); // Our task at hand in this example: Capturing the current moment in UTC.
if ( Boolean.FALSE ) { // Add your Boolean test here to see if the external task is fonud to be completed, as described in this Question.
executor.shutdown (); // 'shutdown' politely asks ScheduledExecutorService to terminate after previously submitted tasks are executed.
}
} catch ( Exception e ) {
System.out.println ( "Oops, uncaught Exception surfaced at Runnable in ScheduledExecutorService." );
}
}
};
try {
executor.scheduleAtFixedRate ( r , 0L , 5L , TimeUnit.SECONDS ); // ( runnable , initialDelay , period , TimeUnit )
Thread.sleep ( TimeUnit.MINUTES.toMillis ( 1L ) ); // Let things run a minute to witness the background thread working.
} catch ( InterruptedException ex ) {
Logger.getLogger ( App.class.getName () ).log ( Level.SEVERE , null , ex );
} finally {
System.out.println ( "ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed." );
executor.shutdown ();
}
Now: 2016-12-27T02:52:14.951Z
Now: 2016-12-27T02:52:19.955Z
Now: 2016-12-27T02:52:24.951Z
Now: 2016-12-27T02:52:29.951Z
Now: 2016-12-27T02:52:34.953Z
Now: 2016-12-27T02:52:39.952Z
Now: 2016-12-27T02:52:44.951Z
Now: 2016-12-27T02:52:49.953Z
Now: 2016-12-27T02:52:54.953Z
Now: 2016-12-27T02:52:59.951Z
Now: 2016-12-27T02:53:04.952Z
Now: 2016-12-27T02:53:09.951Z
ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed.
Now: 2016-12-27T02:53:14.951Z
@Log
@Component
public class ScheduledProcess {
@Scheduled(fixedRate = 5000)
public void run() {
log.info("this runs every 5 seconds..");
}
}
Application.class
@SpringBootApplication
// ADD THIS ANNOTATION TO YOUR APPLICATION CLASS
@EnableScheduling
public class SchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class);
}
}
TimerTask
需要运行55秒,那么它会在每次运行前等待5秒钟,还是像OP所问的那样等待一分钟? - polygenelubricantsschedule
以固定延迟时间执行任务,而scheduleAtFixedRate
则以固定间隔时间执行。很不错! - polygenelubricants