[英]How to execute a task between a certain time period regardless of the Date
I have a Thread in my application which runs continuously till the application is stopped . 我的应用程序中有一个线程,该线程连续运行直到应用程序停止。
I want to change its behavior to run only during the time period from 9 AM to 6 PM regardless of the Date 我想将其行为更改为仅在从上午9点到下午6点的时间段内运行,而不考虑日期
As per the suggestion below , i have done this please let me know if this has got any negative impact . 按照下面的建议,我已经做到了,请告诉我这是否有负面影响。
package com;
import java.util.Calendar;
public class ContinousThread extends Thread {
public void run() {
while (true) {
Calendar c = Calendar.getInstance(); // is automatically initialized to
int hour = c.get(Calendar.HOUR_OF_DAY);
boolean run = hour >= 9 && hour < 18;
if (run) {
doSomething();
} else {
System.out.println("No");
}
}
}
public void doSomething() {
// actual task
}
public static void main(String args[]) {
ContinousThread ct = new ContinousThread();
ct.start();
}
}
Use the Calendars get(field) method to get the hour: 使用Calendars get(field)方法获取小时:
Calendar c = Calendar.getInstance(); // is automatically initialized to current date/time
int hour = c.getField(Calendar.HOUR_OF_DAY);
boolean run = hour >= 9 && hour < 18;
i have done this please let me know if this has got any negative impact
我已经这样做了,请告诉我这是否有负面影响
There is. 有。
boolean run = hour >= 9 && hour < 18;
if (run) {
doSomething();
} else {
System.out.println("No");
}
When run
is false
you have a "busy loop" . 如果
run
为false
,则将出现“忙循环” 。 This will make the cpu busy, very busy. 这会使cpu变得非常繁忙。 And also print tons of
No
on console. 并在控制台上打印大量的
No
One approach is to put a sleep
in the else
block. 一种方法是在
else
块中sleep
。 You can probably sleep for a long time at 18:00
, compute how far you are from the next 9:00
and sleep for that much (or a little less) 您可能可以在
18:00
睡很长时间,计算距下一个9:00
距离,然后睡那么长时间(或少一点)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.