Java每分钟循环一次
我想用Java编写一个循环,firs启动后如下所示:Java每分钟循环一次,java,time,loops,Java,Time,Loops,我想用Java编写一个循环,firs启动后如下所示: while (!x){ //wait one minute or two //execute code } 我想这样做,这样它就不会占用系统资源。代码中实际发生的事情是,它访问一个网站,检查某件事情是否完成,如果没有完成,它应该再等一分钟,直到再次检查,当它完成时,它就继续。他们是否真的要在java中这样做?使用 根据系统计时器和调度程序的精度和准确性,使当前执行的线程休眠(暂时停止执行)指定的毫秒数。线程不会失去任何监视
while (!x){
//wait one minute or two
//execute code
}
我想这样做,这样它就不会占用系统资源。代码中实际发生的事情是,它访问一个网站,检查某件事情是否完成,如果没有完成,它应该再等一分钟,直到再次检查,当它完成时,它就继续。他们是否真的要在java中这样做?使用
根据系统计时器和调度程序的精度和准确性,使当前执行的线程休眠(暂时停止执行)指定的毫秒数。线程不会失去任何监视器的所有权
一分钟等于60000毫秒
例如,此循环将每5秒打印一次当前时间:
try {
while (true) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
如果您的睡眠时间对于int
来说太长,请显式计算long
(例如1000L
)。您可以使用
到时候
timer.cancel();
关闭它。ScheduledExecutorService
接近,但只运行一次。问题似乎是要求无限期运行,直到外部状态发生变化(直到来自网站/服务的响应发生变化)
ScheduledExecutorService
接口是java.util.concurrent包的一部分,该包内置于java 5和更高版本中,作为旧类的更现代的替代品
这是一个完整的例子。调用或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 ();
}
预期输出如下:
while (!x){
//wait one minute or two
//execute code
}
现在:2016-12-27T02:52:14.951Z
现在:2016-12-27T02:52:19.955Z
现在:2016-12-27T02:52:24.951Z
现在:2016-12-27T02:52:29.951Z
现在:2016-12-27T02:52:34.953Z
现在:2016-12-27T02:52:39.952Z
现在:2016-12-27T02:52:44.951Z
现在:2016-12-27T02:52:49.953Z
现在:2016-12-27T02:52:54.953Z
现在:2016-12-27T02:52:59.951Z
现在:2016-12-27T02:53:04.952Z
现在:2016-12-27T02:53:09.951Z
ScheduledExecutorService即将过期。在执行之前提交的任务后,礼貌地要求ScheduledExecutorService终止。
现在:2016-12-27T02:53:14.951Z
如果您使用的是SpringBoot应用程序,它非常简单
计划流程
@Log
@Component
public class ScheduledProcess {
@Scheduled(fixedRate = 5000)
public void run() {
log.info("this runs every 5 seconds..");
}
}
@SpringBootApplication
// ADD THIS ANNOTATION TO YOUR APPLICATION CLASS
@EnableScheduling
public class SchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class);
}
}
应用程序类
@Log
@Component
public class ScheduledProcess {
@Scheduled(fixedRate = 5000)
public void run() {
log.info("this runs every 5 seconds..");
}
}
@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 ask那样等待一分钟?@poly:它会像OP ask那样等待一分钟。“你说什么就做什么。”巴卢斯:啊,真有趣<代码>调度在执行之间以固定的延迟运行,scheduleAtFixedRate
以固定的间隔运行。美好的我尝试了这个方法,并将代码放在run方法中,但在从内部类访问局部变量时出错。@Robert:在这种情况下,请尝试将这些变量设置为final。使用后不要忘记,否则线程将挂起。哦,OP没有要求按固定费率安排日程。请注意,如果线程处于循环中,它不会关闭线程。Shutdownow还会中断线程(您需要处理该线程),您可以使用执行器.newSingleThreadScheduledExecutor()
而不是执行器.newScheduledThreadPool(1)代码>如果您只需要一个线程,我尝试了它,但它不起作用,我的代码如下--if(link.equalsIgnoreCase(“exit”)&count>0{boolean fetched=false;int myCounter=0;尝试{while(!fetched){System.out.println(“Checking”(+myCounter+);if(session.arelinkdonefetch()){session.getFetchData();session.clearList();fetched=true;}myCounter++;Thread.sleep(5*1000);}}}catch(InterruptedException e){e.printStackTrace();}}}你说它“不工作”是什么意思?它不编译吗?它不会一次睡5秒钟?它只运行一次,然后什么也不做。但是程序仍在运行。我的代码有点问题,对不起,它本身运行得很好。不过谢谢你,这正是我个人想要的,我更喜欢解决方案用户下面的Timer
类。