我想在Java中编写一个第一个启动的循环,如下所示:
while (!x){
//wait one minute or two
//execute code
}
我想这样做,以免它耗尽系统资源。在代码中实际发生的是它进入一个网站并检查是否已完成某些事情,如果没有完成,它应该等待一分钟直到它再次检查,并且当它完成时它只是继续。他们无论如何都要在java中这样做吗?
答案 0 :(得分:50)
使当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统定时器和调度程序的精度和准确性。该线程不会失去任何监视器的所有权。
一分钟为(60*1000) = 60000
毫秒。
例如,此循环将每5秒打印一次当前时间:
try {
while (true) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
如果您的睡眠时间对于int
而言过大,请在long
中明确计算(例如1000L
)。
答案 1 :(得分:48)
您可以使用Timer
Timer timer = new Timer();
timer.schedule( new TimerTask() {
public void run() {
// do your work
}
}, 0, 60*1000);
时机成熟
timer.cancel();
关闭它。
答案 2 :(得分:12)
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();
答案 3 :(得分:5)
ScheduledExecutorService
Answer by 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
答案 4 :(得分:0)
如果您使用的是 SpringBoot 应用程序,那就很简单了
预定流程
@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);
}
}