java实现每天8点执行方法A
时间: 2023-10-24 14:10:33 浏览: 49
可以使用Java中的ScheduledExecutorService来实现每天8点执行方法A。具体实现代码如下:
```java
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
long initialDelay = date.getTime() - System.currentTimeMillis();
if (initialDelay < 0) {
initialDelay += 24 * 60 * 60 * 1000;
}
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// 执行方法A
methodA();
}
}, initialDelay, 24 * 60 * 60 * 1000, TimeUnit.MILLISECONDS);
}
public static void methodA() {
// 实现方法A的代码
}
}
```
上述代码中,首先创建了一个ScheduledExecutorService对象executor,然后获取当前时间的Calendar对象,将其设置为当天的8点,得到对应的Date对象。计算出第一次执行的延迟时间initialDelay,如果当前时间已经过了8点,则需要加上一天的时间。然后使用executor.scheduleAtFixedRate()方法来执行方法A,指定了初始延迟时间initialDelay和固定的周期为24小时。这样就可以每天8点执行方法A了。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)